Advertisement
MerAll

StrutsCart:ProductsDBDAO

Aug 30th, 2014
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.96 KB | None | 0 0
  1. package daos;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.util.ArrayList;
  9. import java.util.Arrays;
  10. import java.util.List;
  11.  
  12. import pojos.Product;
  13. import exceptions.DBIntegrityException;
  14.  
  15. /**DAO that handles interaction with the Products Database.
  16.  *
  17.  
  18. USE merwebappdb;
  19. CREATE TABLE products(
  20.     product_name VARCHAR(255) NOT NULL,
  21.     product_id INT UNIQUE NOT NULL,
  22.     price DOUBLE NOT NULL,
  23.     modified_date  TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  24.     PRIMARY KEY(product_id)
  25.     );
  26.  *
  27.  * @author Meredith Allen
  28.  * TODO: modify this to run on server with JNDI data source after completion of local
  29.  * testing with basic JDBC Connection methods.
  30.  *
  31.  */
  32. public class ProductsDBDao {
  33.    
  34.     private static final String DB_CONN_STRING = "jdbc:mysql://localhost:3306/merwebappdb";
  35.     private static final String DB_USER="root";
  36.     private static final String DB_PASSWORD="censored";
  37.    
  38.     private static final String ADD_PRODUCT_SQL="INSERT INTO products(product_name,product_id,price) VALUES(?,?,?)";
  39.     private static final String DROP_ALL_PRODUCTS_SQL= "DELETE FROM products"; //shouldn't be used outside of testing.
  40.     private static final String SELECT_ALL_PRODUCTS_SQL="SELECT * FROM products";
  41.     private static final String SELECT_PRODUCT_BY_ID_SQL="SELECT FROM products WHERE product_id=?";
  42.    
  43.    
  44.     static{
  45.     try {
  46.         Class.forName("com.mysql.jdbc.Driver");
  47.     } catch (ClassNotFoundException e) {
  48.          e.printStackTrace();
  49.     }
  50.     }
  51.    
  52.     public ProductsDBDao() {
  53.  
  54.     }
  55.    
  56.     /**Will fail on attempt to insert duplicate product ids.*/
  57.     public synchronized void insertProduct(String productName, int productId, double productPrice)
  58.     {
  59.     try(Connection con = DriverManager.getConnection(DB_CONN_STRING,DB_USER,DB_PASSWORD);
  60.         PreparedStatement ps = con.prepareStatement(ADD_PRODUCT_SQL)){
  61.         ps.setString(1, productName);
  62.         ps.setInt(2, productId);
  63.         ps.setDouble(3, productPrice);
  64.         ps.execute();
  65.        
  66.     } catch (SQLException e) {
  67.         System.err.printf("UPDATE FAILED (%s,%d,%f).%n",productName,productId,productPrice);
  68.         e.printStackTrace();
  69.     }
  70.     }
  71.    
  72.     /**Overloaded. Calls base insertProduct method.
  73.      * Will fail on attempt to insert duplicate product ids.*/
  74.     public synchronized void insertProduct(Product p)
  75.     {
  76.     insertProduct(p.getProductName(),p.getProductId(),p.getPrice());
  77.     }
  78.    
  79.     public synchronized void insertProducts(List<Product> products)
  80.     {
  81.     for(Product p:products)
  82.     {
  83.         insertProduct(p);
  84.     }
  85.    
  86.     }
  87.    
  88.     /**Drop all products (not a normal circumstance of operation.  May cause
  89.      * problems if the system was relying on ids corresponding to specific products
  90.      * and those are changed on next update.
  91.      *
  92.      */
  93.     public void clearProductsTable(){
  94.     try(Connection conn=DriverManager.getConnection(DB_CONN_STRING, DB_USER, DB_PASSWORD);
  95.         PreparedStatement ps = conn.prepareStatement(DROP_ALL_PRODUCTS_SQL)){
  96.        ps.execute();
  97.        
  98.     } catch (SQLException e) {
  99.         System.err.println("FAILED ON ATTEMPT TO CLEAR PRODUCTS TABLE.");
  100.         e.printStackTrace();
  101.     }
  102.     }
  103.    
  104.     /**Get a full set of Products listed in the database as Product objects.
  105.      *
  106.      * @return List of products in database
  107.      */
  108.     public List<Product> getAllProducts(){
  109.     List<Product> products = new ArrayList<Product>();
  110.     try(Connection conn=DriverManager.getConnection(DB_CONN_STRING, DB_USER, DB_PASSWORD);
  111.         PreparedStatement ps = conn.prepareStatement(SELECT_ALL_PRODUCTS_SQL)){
  112.        if(ps.execute()) //true indicates that ResultSet was stored in PreparedStatement object.
  113.        {
  114.            ResultSet rs = ps.getResultSet();
  115.            while(rs.next())
  116.            {
  117.            String name="";
  118.            int id=0;
  119.            double price=0;
  120.              name= rs.getString("product_name");
  121.                id=rs.getInt("product_id");
  122.                price= rs.getDouble("price");
  123.            Product p = new Product(name,id,price);
  124.            products.add(p);
  125.          
  126.          }
  127.  
  128.            
  129.        }
  130.        
  131.        
  132.     } catch (SQLException e) {
  133.         System.err.println("FAILED ON ATTEMPT TO SELECT ALL PRODUCTS FROM TABLE.");
  134.         e.printStackTrace();
  135.     }
  136.     return products;
  137.     }
  138.     public Product getProductById(int id)
  139.     {
  140.     Product product = null;
  141.     try(Connection conn=DriverManager.getConnection(DB_CONN_STRING, DB_USER, DB_PASSWORD);
  142.         PreparedStatement ps = conn.prepareStatement(SELECT_PRODUCT_BY_ID_SQL)){
  143.             if(ps.execute()) //should return true (indicating ps contains ResultSet
  144.             {
  145.                 ResultSet rs = ps.getResultSet();
  146.                 if(rs.next()){  //verify at least one result
  147.                
  148.                
  149.                 if(rs.next())
  150.                 {
  151.                     throw new DBIntegrityException("Retrieved more than one product for a given id.  This should not have happened.");
  152.                 }
  153.                
  154.                 }else{  //if no results, item was not found.
  155.                
  156.                
  157.                 }
  158.             }
  159.     } catch (SQLException e) {
  160.         e.printStackTrace();
  161.     } catch (DBIntegrityException e) {
  162.         e.printStackTrace();
  163.     }
  164.     return null;
  165.    
  166.     }
  167.    
  168.     public static void main(String[] args) {
  169.    
  170.     ProductsDBDao pdbd = new ProductsDBDao();
  171.     pdbd.clearProductsTable();
  172.     pdbd.insertProduct("TESTPRODUCT", 5, 3.00);
  173.     pdbd.insertProduct("TESTPRODUCT2", 6, 6.00);
  174.     pdbd.insertProducts(Arrays.asList(new Product("TESTPRODUCT3",7,8.00),
  175.         new Product("TESTPRODUCT4",8,9.00)));
  176.     //This one has a duplicate and should fail after the first add.
  177.     pdbd.insertProducts(Arrays.asList(new Product("TESTPRODUCT5",9,11.00),
  178.         new Product("TESTPRODUCT6SHOULDFAIL",8,9.00),
  179.         new Product("TESTPRODUCT7WILLSTILLBEADDED",10,9.00)
  180.         ));
  181.    
  182.     for(Product p:pdbd.getAllProducts())
  183.         System.out.printf("PRODUCT:\t%s\t%d\t%f%n",p.getProductName(),p.getProductId(),p.getPrice());
  184.    
  185.    
  186.     }
  187. }
  188.  
  189. /*Sample output (note the rejection of the duplicate id 8.):
  190.  * UPDATE FAILED (TESTPRODUCT6SHOULDFAIL,8,9.000000).
  191. com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '8' for key 'P
  192. RIMARY'
  193.     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931)
  194.     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
  195.     at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
  196.     at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
  197.     at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
  198.     at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
  199.     at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:882)
  200.     at daos.ProductsDBDao.insertProduct(ProductsDBDao.java:64)
  201.     at daos.ProductsDBDao.insertProduct(ProductsDBDao.java:76)
  202.     at daos.ProductsDBDao.insertProducts(ProductsDBDao.java:83)
  203.     at daos.ProductsDBDao.main(ProductsDBDao.java:177)
  204. PRODUCT:    TESTPRODUCT 5   3.000000
  205. PRODUCT:    TESTPRODUCT2    6   6.000000
  206. PRODUCT:    TESTPRODUCT3    7   8.000000
  207. PRODUCT:    TESTPRODUCT4    8   9.000000
  208. PRODUCT:    TESTPRODUCT5    9   11.000000
  209. PRODUCT:    TESTPRODUCT7WILLSTILLBEADDED    10  9.000000
  210.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement