DAO mode and singleton mode

Why JDBC package 2-1

1. Extract and encapsulate codes with similar functions into methods to reduce code redundancy

2. Because different databases have different implementations, database operations are generally extracted into interfaces, which can reduce coupling in future development
Insert picture description here

  1. Isolate business logic code and data access code
  2. Isolate the implementation of different databases

Insert picture description here

Implement JDBC package

  • Extract all add, delete, modify, and check operations into interfaces
  • Define entity class to transmit data
  • Encapsulate common operations (opening, closing connections, etc.) into tool classes
  • Database tools BaseDao: general methods for adding, deleting, modifying and checking
public class BaseDao {
    public Connection getConn() throws Exception {
        //加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://192.168.83.35:3306/MySchool";
        //驱动管理器来获取连接
        Connection conn= DriverManager.getConnection(url,"root","ok");
        return conn;
    }
    public void showTables() throws Exception {
        //获取连接
        Connection conn=getConn();
     //先获取Statement对象
        Statement stmt=conn.createStatement();
        String sql="show tables";
        ResultSet rs = stmt.executeQuery(sql);
        while(rs.next()){
            System.out.println(rs.getString("Tables_in_MySchool"));
        }
    }


    public ResultSet query(String sql) throws Exception{
        Connection conn=getConn();
        Statement stmt=conn.createStatement();
        String sql1=sql;
        ResultSet rs = stmt.executeQuery(sql1);
        return  rs;
    }
    
    public int update(String sql)throws Exception{
        Connection conn=getConn();
        Statement stmt=conn.createStatement();
        int i = stmt.executeUpdate(sql);
        return  i;


    }
}
package demo;


import entiry.Student;
import org.junit.Test;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;


import static org.junit.Assert.*;


public class BaseDaoTest {


    @Test
    public void getConn() throws Exception {
        BaseDao dao=new BaseDao();
        Connection conn=dao.getConn();
        System.out.println(conn);
    }


    @Test
    public void showTables() throws Exception {
        BaseDao dao=new BaseDao();
        dao.showTables();
    }
    @Test
    public  void query() throws Exception {
        BaseDao dao=new BaseDao();
        String sql="select * from student";
        ResultSet rs=dao.query(sql);
        ArrayList<Student> stulist=new ArrayList<>();
        while (rs.next()){
            Student s=new Student();
            s.setStudentNo(rs.getInt("StudentNo"));
            s.setStudentName(rs.getString("StudentName"));
            stulist.add(s);
        }
        for (Student student : stulist) {
            System.out.println(student);
        }


    }


    @Test
    public void update() throws Exception {
        BaseDao dao=new BaseDao();
        String sql="insert into student(StudentNo,StudentName) "+
                "values(1011,'一灯'),(1065,'因故')";
        int num=dao.update(sql);
        System.out.println(num > 0 ? "插入成功" : "插入失败");
    }
    //使用jdbc创建一个库,切换到这个库,创建一个表
    @Test
    public void testDo() throws Exception{
        BaseDao dao=new BaseDao();
        Connection conn=dao.getConn();
        Statement stmt=conn.createStatement();
        String createDabase="create database if not exists userControl";
        boolean isSuccess = stmt.execute(createDabase);
        System.out.println(isSuccess);
        String changeDatabase="use userControl";
        stmt.execute(changeDatabase);
        String createTable="create table user_info(" +
                "uid int(11) auto_increment primary key," +
                "uname varchar(30)," +
                "password varchar(30))";
        stmt.execute(createTable);
    }
}

What is DAO

  • Data Access Object
  • Between business logic and persistent data
  • Achieve access to persistent data

Insert picture description here

The composition of the DAO model

Components of the DAO model

  • DAO interface
  • DAO implementation class
  • Entity class
  • Database connection and closing tools

Advantage

  • Isolate data access code and business logic code
  • Isolate different database implementations

Configure database access parameters

Disadvantages

When the database changes, re-modify the code, recompile and deploy

solve

Write the database information in the configuration file and let the program obtain this information by reading the configuration file

Properties file

  • The suffix is ​​.properties
  • The data format is "key=value"
  • Use "#" to comment
    Insert picture description here
package demo;


import until.Prop;


import java.sql.*;


/**
* @Author lichangxin
* @date 2020-08-21
* @Des
*/


public class PstDao {
    private static String driver= Prop.getP("driver");
    private static String url=Prop.getP("url");
    private static String user=Prop.getP("user");
    private static String pwd=Prop.getP("pwd");


    public static Connection getConn(){
        try {
            Class.forName(driver);
            return DriverManager.getConnection(url,user,pwd);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void close(Connection conn, PreparedStatement pst, ResultSet rs){
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pst!=null){
            try {
                pst.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    public static ResultSet query(String sql,Object ...params ){
        Connection conn = getConn();
        PreparedStatement pst=null;
        ResultSet rs=null;
        try {
             pst=conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pst.setObject(i+1,params[i]);
            }
            rs=pst.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
//            close(conn,pst,null);
        }
        return rs;
    }


    public static int update(String sql,Object...params){
        Connection conn=getConn();
        PreparedStatement pst=null;
        try {
            pst=getConn().prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pst.setObject(i+1,params[i]);
            }
            return pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {if (pst!=null) {
                pst.close();
            }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn!=null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return -1;


    }
}
package demo;


import org.junit.Test;


import java.sql.ResultSet;
import java.sql.SQLException;


import static org.junit.Assert.*;


public class PstDaoTest {


    @Test
    public void query() throws SQLException {
        String sql="SELECT SubjectName,score FROM `subject` s " +
                "JOIN result r ON s.SubjectNo=r.sub_no WHERE score>? AND SubjectName IN(?,?)";
        ResultSet rs=PstDao.query(sql,60,"高等数学-1","高等数学-2");
        while (rs.next()){
            System.out.print(rs.getString("SubjectName")+"----");
            System.out.println(rs.getInt("score"));
        }
        rs.close();
    }


    @Test
    public void update(){
        String sql="update account set cash=cash+? where name=?";
        int num=PstDao.update(sql,10000,"icbc");
        System.out.println(num > 0 ? "更新成功" : "更新失败");
    }
}
package until;


import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;


/**
* @Author lichangxin
* @date 2020-08-21
* @Des
*/


public class Prop {
    private  static Properties p=new Properties();
    public  static String getP(String param){
        try {
            p.load(new FileInputStream("resources/db.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return p.getProperty(param);
    }
}
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.83.35:3306/shop
user=root
pwd=ok

Why singleton mode is needed

  • BaseDao: The base class for operating the database
  • Each thread needs a new instance of BaseDao for system operations
  • I/O operations during initialization consume system resources and affect system performance

系统运行期间,有且仅有一个实例

There is only one instance of a class-the most basic requirement

Only provide private constructor

It must create this instance by itself

Defines static private objects of this type

It must report to the entire system

Provide this instance to provide a static public method, return to create or obtain its own static private object

Lazy man

The instance is not created when the class is loaded, and the method of lazy loading is adopted, and the instance is created when the call is run.
Features

  1. Thread unsafe
  2. Lazy loading

How to solve thread safety issues?
Synchronized

Hungry man mode

When the class is loaded, the initialization feature is completed

  1. Thread safe
  2. Does not have lazy loading features
Singleton mode Lazy man Hungry man mode
concept The instance is not created when the class is loaded, and the method of lazy loading is used to create the instance when the call is run When the class is loaded, the initialization is completed
Features The class loads fast, but the speed of obtaining objects at runtime is slow. ——"Time for Space" Class loading is slower, but object acquisition speed is faster. ——"Space for Time"
Lazy loading (lazy loa ding) have Do not have
Thread safe Thread unsafe Thread safe

Guess you like

Origin blog.csdn.net/zmzdmx/article/details/108207091