The proxy class implements the Java connection database of using the dao layer to operate data instance sharing

  • 2020-04-01 02:38:29
  • OfStack

First, we define the structure type to be stored in a Java file:


import java.util.Date ;

public class Emp {
    private int empno ;
    private String ename ;
    private String job ;
    private Date hiredate ;
    private float sal ;
    public void setEmpno(int empno){
        this.empno = empno ;
    }
    public void setEname(String ename){
        this.ename = ename ;
    }
    public void setJob(String job){
        this.job = job ;
    }
    public void setHiredate(Date hiredate){
        this.hiredate = hiredate ;
    }
    public void setSal(float sal){
        this.sal = sal ;
    }
    public int getEmpno(){
        return this.empno ;
    }
    public String getEname(){
        return this.ename ;
    }
    public String getJob(){
        return this.job ;
    }
    public Date getHiredate(){
        return this.hiredate ;
    }
    public float getSal(){
        return this.sal ;
    }
}

Let's define a database connection class that initiates a connection to the database. Java connection database requires driver package, we can download by ourselves, I used mysql-connector-java-5.0.5-bin.jar in the test. When running the program, Eclipse will prompt the database Driver package to be loaded, some of which are standard packages like "org.gjt.mm.mysql.driver". Generally speaking, we can choose the Driver package in the working directory.


import java.sql.Connection ;
import java.sql.DriverManager ;

public class DatabaseConnection {
    private static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ; 
    private static final String DBURL = "jdbc:mysql://localhost:3306/mldn" ;
    private static final String DBUSER = "root" ;
    private static final String DBPASSWORD = "root" ;
    private Connection conn ;
    public DatabaseConnection() throws Exception {
        Class.forName(DBDRIVER) ;
        this.conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD) ;
    }
    public Connection getConnection(){
        return this.conn ;
    }
    public void close() throws Exception {
        if(this.conn != null){
            try{
                this.conn.close() ;
            }catch(Exception e){
                throw e ;
            }
        }
    }
}

Next we define an interface that helps us easily implement the proxy method. There are only three methods in the interface: insert, find all, and find by ID.


import java.util.* ;

public interface IEmpDAO {
    public boolean doCreate(Emp emp) throws Exception ;
    public List<Emp> findAll(String keyWord) throws Exception ;
    public Emp findById(int empno) throws Exception ;
}

And then, we inherit the interface, and we implement the database-specific operation classes, which are very basic database operations, nothing to talk about. The main thing to note is that in the constructor, the Connection object is used as an argument, and the Connection object returned by the function getConnection() from the DatabaseConnection class defined earlier is passed in when this class is used.


import java.sql.* ;

public class EmpDAOImpl implements IEmpDAO{
    private Connection conn = null ;
    private PreparedStatement pstmt = null ;
    public EmpDAOImpl(Connection conn)
    {
        this.conn = conn;
    }
    public boolean doCreate(Emp emp) throws Exception{
        boolean flag = false;
        String sql = "INSERT INTO emp(empno,ename,job,hiredate,sal) VALUES(?,?,?,?,?)";
        this.pstmt = this.conn.prepareStatement(sql);
        this.pstmt.setInt(1, emp.getEmpno());
        this.pstmt.setString(2,emp.getEname()) ;
    this.pstmt.setString(3,emp.getJob()) ;
    this.pstmt.setDate(4,new java.sql.Date(emp.getHiredate().getTime())) ;
    this.pstmt.setFloat(5,emp.getSal()) ;
        if(this.pstmt.executeUpdate() > 0)
        {
            flag = true;
        }
        this.pstmt.close();
        return flag;
    }
    public List<Emp> findAll(String keyWord) throws Exception{
        List<Emp> all = new ArrayList<Emp>();
        String sql = "SELECT empno,ename,job,hiredate,sal FROM emp WHERE ename LIKE ? OR job LIKE ?";
        this.pstmt = this.conn.prepareStatement(sql);
        this.pstmt.setString(1,"%"+keyWord+"%"); //Escape character
        this.pstmt.setString(2,"%"+keyWord+"%");
        ResultSet rs = this.pstmt.executeQuery(sql);
        Emp emp = null;
        while(rs.next())
        {
            emp = new Emp();
            emp.setEmpno(rs.getInt(1));
            emp.setEname(rs.getString(2)) ;
        emp.setJob(rs.getString(3)) ;
        emp.setHiredate(rs.getDate(4)) ;
        emp.setSal(rs.getFloat(5)) ;
            all.add(emp);
        }
        this.pstmt.close();
        return all;
    }
    public Emp findById(int empno) throws Exception{
        Emp emp = null ;
        String sql = "SELECT empno,ename,job,hiredate,sal FROM emp WHERE empno=?" ;
        this.pstmt = this.conn.prepareStatement(sql) ;
        this.pstmt.setInt(1,empno) ;
        ResultSet rs = this.pstmt.executeQuery() ;
        if(rs.next()){
            emp = new Emp() ;
            emp.setEmpno(rs.getInt(1)) ;
            emp.setEname(rs.getString(2)) ;
            emp.setJob(rs.getString(3)) ;
            emp.setHiredate(rs.getDate(4)) ;
            emp.setSal(rs.getFloat(5)) ;
        }
        this.pstmt.close() ;
        return emp ;
    }    
}

Now let's take a look at the implementation of the proxy class, where I find it interesting. In this class, declare a database connection class DatabaseConnection objects, a database application class the EmpDAOImpl object, use the DatabaseConnection object initialization the EmpDAOImpl object, and then in the proxy class USES the EmpDAOImpl objects to each function call inherited from the same interface method, which to a certain degree of hidden concrete realization method.


import java.sql.* ;

public class EmpDAOProxy implements IEmpDAO{
    private DatabaseConnection dbc = null ;
    private EmpDAOImpl dao = null ;
    public EmpDAOProxy() throws Exception{
        this.dbc = new DatabaseConnection();
        this.dao = new EmpDAOImpl(this.dbc.getConnection());
    }
    public boolean doCreate(Emp emp) throws Exception{
        boolean flag = false;
        try{
            if(this.dao.findById(emp.getEmpno()) == null)
            {
                flag = this.dao.doCreate(emp);

            }
        }catch(Exception e)
        {
            throw e;
        }finally{
            this.dbc.close();
        }
        return flag;
    }
    public List<Emp> findAll(String keyWord) throws Exception{
        List<Emp> all = null ;
        try{
            all = this.dao.findAll(keyWord) ;
        }catch(Exception e){
            throw e ;
        }finally{
            this.dbc.close() ;
        }
        return all ;
    }
    public Emp findById(int empno) throws Exception{
        Emp emp = null ;
        try{
            emp = this.dao.findById(empno) ;
        }catch(Exception e){
            throw e ;
        }finally{
            this.dbc.close() ;
        }
        return emp ;
    }
}

This is not all, we can add a factory class to implement the factory pattern:



public class DAOFactory {
    public static IEmpDAO getIEmpDAOInstance() throws Exception{
        return new EmpDAOProxy() ;
    }
}

What is the use of this factory class? Finally we make the call in the main class file to see what the factory class does:



public class TestDAOInsert {
    public static void main(String args[]) throws Exception{
        Emp emp = null ;
        for(int x=0;x<5;x++){
            emp = new Emp() ;
            emp.setEmpno(1000 + x) ;
            emp.setEname(" Chinese display test  - " + x) ;
            emp.setJob(" The programmer  - " + x) ;
            emp.setHiredate(new java.util.Date()) ;
            emp.setSal(500 * x) ;
            DAOFactory.getIEmpDAOInstance().doCreate(emp) ;
        }
    }
}

It can be seen that the specific implementation method is better hidden. The proxy class is obtained by calling the get method through the factory class. The proxy class calls the specific method, and then the specific operation object in the proxy class calls the specific operation method.

In fact, these things may seem very simple, but they are often forgotten when they are designed by themselves. Mainly because of the use of it is not much, always have to force themselves to do, and then slowly become a habit.


Related articles: