当前位置:网站首页>Jdbc-dao layer implementation

Jdbc-dao layer implementation

2022-06-25 08:14:00 Maximize+

Let's briefly talk about DAO Layer implementation logic
First, create an abstract class BaseDAO, Declare the method of adding, deleting, modifying and querying in this abstract class ; Second, create a CustomersDAO The interface of , Used to write specifications ; Create an implementation class , Inherit BaseDAO Abstract classes and introduce interfaces CUstmersDAO Interface , Rewrite the method ; Create a test class , Create transaction code and execute .

BaseDAO abstract class

package dao;

import JDBCUtils.JDBCUtils;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

/*  Encapsulates general operations for data tables  */
public abstract class BaseDAO {
    
    // Consider the general addition, deletion and modification of transactions 
    //update The method parameter of is 
    /* Connection conn:JDBC Connecting bridges  String sql:MySQL Execute statement  Object...args: Generic type array ( Deformable parameter syntax )  return int Used to check whether the execution is successful  */
    public int update(Connection conn,String sql,Object...args){
    
        // Create a PreparedStatement Object is temporarily assigned to Null The object variable is recognized by the scope when the syntax is used to close the resource 
        PreparedStatement ps = null;//PreparedStatement Is an access operation SQL Statement 
        try{
    
            ps = conn.prepareStatement(sql);// Assign values and precompile SQL sentence 
            // Do placeholder fill traversal   Use incoming Object The array length is the number of iterations 
            for(int i=0;i<args.length;i++){
    
                // Fill placeholders , Because the value of the loop variable is from 0 At the beginning , however MySQL The index of all is 1 At the beginning 
                // So the index filling here must be i+1, from 1 Start execution , fill args Of i Index content 
                ps.setObject(i+1,args[i]);
            }
            // Return direct results   The return type is int  If the execution is successful, it is 1+, Execution failed as 0
            // You can use a variable to obtain the return value for judgment 
            //int flag = ps.executeUpdate if(ps==0){System.out.println(" Execution failure ")}else{System.out.println(" Successful implementation ")}
            return ps.executeUpdate();
        }catch (Exception ex){
    
            // Print exception log 
            ex.printStackTrace();
        }finally {
    //finally Is a statement that must be executed , So don't put... Here return 0 perhaps  return null
            JDBCUtils.closeResource(null,ps);// This method is the closing resource method of the custom tool class , Algorithm for : if(!=null) close  Avoid null pointer exceptions 
        }
        return 0;// If the above code is not executed or successfully executed, return here   Here is the final result 
    }
    // Consider the general query operation of transactions 
    // General single query results are complex 
    /*  First, the return value is a T Generic   Method signature is : Connection conn: One JDBC Connecting bridges  Class<T>clazz: Kind of generic  String sql:MySQL Execute statement  Object...args: Deformable parameter group  */
    public <T> T getInstance(Connection conn,Class<T>clazz,String sql,Object...args){
    
        // Precompile interface 
        PreparedStatement ps = null;
        //rs Result set , Queries are result sets that hold the data 
        ResultSet rs = null;
        // The declaration here is to locate and identify the variable object when the tool class is closed 
        try{
    
            // To initialize 
            ps = conn.prepareStatement(sql);
            // Fill in placeholders 
            for(int i=0;i<args.length;i++){
    
                ps.setObject(i+1,args[i]);
            }
            // Get the result set 
            rs = ps.executeQuery();
            // Get result set metadata , The metadata contains the number of data rows   Row name   Etc 
            ResultSetMetaData rsmd = rs.getMetaData();
            int coulumnCount = rsmd.getColumnCount();// Get the number of metadata rows 
            if(rs.next()){
    // If rs The result set also has content 
                T t = clazz.newInstance();// Generic initialization   This is equivalent to getting the incoming formal parameter object 
                for(int i=0;i<coulumnCount;i++){
    // Traversal   Traversing the number of rows 
                    // Get column values 
                    Object columnValue = rs.getObject(i+1);// Because the index started from the beginning 
                    String columnLabel = rsmd.getColumnLabel(i+1);// What is called here is the method that can identify the database alias , For another  getColumnName
                    /*  Recommended here  rsmd.getColumnLabel Method , Because this method can identify aliases , It is used to solve the problem of non docking of encapsulated class data , And although no alias is used   The effect will also be similar to getColumnName The effect is consistent  */

                    // Assignment by reflection 
                    Field field = clazz.getDeclaredField(columnLabel);// Here we get the field properties corresponding to the encapsulation class 
                    field.setAccessible(true);// Set permissions to true Avoid insufficient permissions 
                    field.set(t,columnValue);// Assign a value , object + Result set data 
                }
                return t;
            }
        }catch (Exception ex){
    
            ex.printStackTrace();// Print exception log 
        }finally {
    // Must execute statement 
            JDBCUtils.closeResource(null,ps,rs);// close resource , here conn Close as null
            /*  by null To implement transactions , The connections of transactions are the same , Closing the connection will cause the database to submit data automatically , It destroys the order of affairs   There is no need to worry about passing in parameters Null Null pointer exception will be reported , Because our algorithm judges that  if(conn != null){ conn.close(); }  This resource can only be closed if it is not empty , Otherwise, there is no change operation  */
        }
        return null;// This result is returned if the top-down execution is not successful or not executed , This result is the final result 
    }
    // A general method for multi row query results 
    // The method signature here is consistent with the above procedure 
    // The return value represents a generic collection   Its declaration type is generic   Saving content is also generic 
    public <T>List<T> getForList(Connection conn,Class<T>clazz,String sql,Object...args){
    
        PreparedStatement ps = null;// Precompiled execution statement declaration 
        ResultSet rs = null;// Result set declaration 
        try{
    
            ps = conn.prepareStatement(sql);// Precompiled execution initialization 
            for(int i=0;i<args.length;i++){
    // Place holder to fill 
                ps.setObject(i+1,args[i]);
            }
            rs = ps.executeQuery();// Result set acquisition 
            ResultSetMetaData rsmd = rs.getMetaData();// Metadata access 
            int columnCount = rsmd.getColumnCount();// Metadata row number acquisition 
            ArrayList<T>list = new ArrayList<T>();// initialization List object   Here is ArrayList<T>
            while (rs.next()){
    // Use while Determine the next row of the result set 
                T t = clazz.newInstance();// initialization clazz Get the object 
                for(int i =0;i<columnCount;i++){
    // Traverse the number of rows 
                    Object columnValue = rs.getObject(i+1);// The initial index is 1  get data 
                    String columnLabel = rsmd.getColumnLabel(i+1);// Get the corresponding field 
                    Field field = clazz.getDeclaredField(columnLabel);// Get the field corresponding to the class 
                    field.setAccessible(true);// Set public permissions 
                    field.set(t,columnValue);// Perform data filling. Note that here is  for Statements in a loop 
                }
                list.add(t);// Add object , Notice here is while A statement in a loop statement 
                // The most common is  while  set  for Circulated  while The loop is simple and clear   The efficiency and simplicity of simple single data traversal are very good 
            }
            return list;// Finally, return the array , This array holds all the query results 
        }catch(Exception ex){
    
            ex.printStackTrace();// Print exception log 
        }finally {
    // Must execute statement 
            JDBCUtils.closeResource(null,ps,rs);// close resource , Consider that transactions are not closed conn Connecting bridge 
        }
        return null;// final result   return null
    }
    public <E>E getValue(Connection conn,String sql,Object...args){
    
        PreparedStatement ps = null;
        ResultSet rs = null;// Get the result set 
        try {
    
            // obtain PreparedStatement Instance precompiled SQL sentence 
            ps = conn.prepareStatement(sql);
            // Fill in placeholders 
            for(int i=0;i<args.length;i++){
    
                ps.setObject(i+1,args[i]);
            }// Result set 
            rs = ps.executeQuery();

            if(rs.next()){
    // Access to type 
                return (E)rs.getObject(1);
            }
        } catch (Exception throwables) {
    
            throwables.printStackTrace();// Print exception log 
        } finally {
    
            JDBCUtils.closeResource(null,ps,rs);// close resource 
        }
        return null;
    }
}

CustomersDAO Interface class

package dao;

import oldJDBCTest.Customer;

import java.sql.Connection;
import java.sql.Date;
import java.util.List;

// For specifications Customer Table operations 
public interface CustomerDAO {
    
    void insert(Connection conn, Customer cust);

    void deleteById(Connection conn,int id);

    void update(Connection conn,Customer cust);

    Customer  getCustomerById(Connection conn,int id);

    List<Customer> getAll(Connection conn);

    Long getCount(Connection conn);

    Date getMaxBirth(Connection conn);
}

CustomerDAOImpl Implementation class

package dao;

import oldJDBCTest.Customer;

import java.sql.Connection;
import java.sql.Date;
import java.util.List;

public class CustomerDAOImpl extends BaseDAO implements CustomerDAO {
    

    @Override
    public void insert(Connection conn, Customer cust) {
    
        String sql = "insert into customers(name,email,birth)values(?,?,?)";
        update(conn,sql,cust.getName(), cust.getEmail(),cust.getBirth());
    }

    @Override
    public void deleteById(Connection conn, int id) {
    
        String sql = "delete from customers where id = ?";
        update(conn,sql,id);
    }

    @Override
    public void update(Connection conn, Customer cust) {
    
        String sql = "update customers set name = ?,email=?,birth=? where id = ?";
        update(conn,sql,cust.getName(),cust.getEmail(),cust.getBirth(),cust.getId());
    }

    @Override
    public Customer getCustomerById(Connection conn, int id) {
    
        String sql  = "select id,name,email,birth from customers where id = ?";
        Customer customer = getInstance(conn, Customer.class,sql,id);
        return customer;
    }

    @Override
    public List<Customer> getAll(Connection conn) {
    
        String sql = "select id,name,email,birth from customers";
        List<Customer> forList = getForList(conn, Customer.class, sql);
        return forList;
    }

    @Override
    public Long getCount(Connection conn) {
    
        String sql = "select count(*) from customers";
        return getValue(conn,sql);
    }

    @Override
    public Date getMaxBirth(Connection conn) {
    
        String sql = "select max(birth) from customers";
        return getValue(conn,sql);
    }
}

CustomerDAOImplTest Test class

package dao;

import JDBCUtils.JDBCUtils;
import oldJDBCTest.Customer;

import java.sql.Connection;
import java.sql.Date;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

public class CustomerDAOImplTest {
    
    private CustomerDAOImpl dao = new CustomerDAOImpl();

    @org.junit.jupiter.api.Test
    void insert() {
    
        Connection conn = null;
        try{
    
           conn = JDBCUtils.getConnection();
            Customer cust = new Customer(1," Yu Xiaofei ","[email protected]",new Date(1545154455L));
            dao.insert(conn,cust);
            System.out.println(" Add success ");
        }catch (Exception ex){
    
            ex.printStackTrace();
        }finally {
    
            JDBCUtils.closeResource(conn,null);
        }
    }

    @org.junit.jupiter.api.Test
    void deleteById() {
    
        Connection conn = null;
        try {
    
            conn = JDBCUtils.getConnection();
            dao.deleteById(conn,5);
            System.out.println(" Delete successful ");
        }catch (Exception ex){
    
            ex.printStackTrace();
        }finally {
    
            JDBCUtils.closeResource(conn,null);
        }
    }

    @org.junit.jupiter.api.Test
    void update() {
    
        Connection conn = null;
        try {
    
            conn = JDBCUtils.getConnection();
            Customer cust = new Customer(9," Beethoven ","[email protected]",new Date(453465656L));
            dao.update(conn,cust);
            System.out.println(" Modification successful ");
        }catch (Exception ex){
    
            ex.printStackTrace();
        }finally {
    
            JDBCUtils.closeResource(conn,null);
        }
    }

    @org.junit.jupiter.api.Test
    void getCustomerById() {
    
        Connection conn = null;
        try{
    
            conn = JDBCUtils.getConnection();
            Customer customer = dao.getCustomerById(conn,7);
            System.out.println(customer);
        }catch (Exception ex) {
    
            ex.printStackTrace();
        }finally {
    
            JDBCUtils.closeResource(conn,null);
        }
    }

    @org.junit.jupiter.api.Test
    void getAll() {
    
        Connection conn = null;
        try {
    
            conn = JDBCUtils.getConnection();
            List<Customer> all = dao.getAll(conn);
            all.forEach(System.out::println);
        }catch (Exception ex){
    
            ex.printStackTrace();
        }finally {
    
            JDBCUtils.closeResource(conn,null);
        }
    }

    @org.junit.jupiter.api.Test
    void getCount() {
    
        Connection conn = null;
        try {
    
            conn = JDBCUtils.getConnection();
            Long count = dao.getCount(conn);
            System.out.println(" Number of records in the table :"+count);
        }catch (Exception ex){
    
        ex.printStackTrace();
        }finally {
    
        JDBCUtils.closeResource(conn,null);
        }
 }

    @org.junit.jupiter.api.Test
    void getMaxBirth() {
    
        Connection conn = null;
        try {
    
            conn = JDBCUtils.getConnection();
            Date maxBirth = dao.getMaxBirth(conn);
            System.out.println(" The biggest birthday is :"+maxBirth);
        }catch (Exception ex){
    
            ex.printStackTrace();
        }finally {
    
            JDBCUtils.closeResource(conn,null);
        }
    }
}
原网站

版权声明
本文为[Maximize+]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250542552032.html