Dao layer design, JdbcUtils class, database connection pool technology

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/MacWx/article/details/90666096

1 Dao design philosophy
when the Java language to operate the database tables inside data to be used jdbc, but jdbc code is very tedious, if the regular operation of the data, will be high repeatability of these codes. Therefore, we often related to the operation of our package dao table class. This improves the efficiency of the code, to improve the maintainability of the system scalability.
Dao (data access object) data access object.

Dao which requires the following components:

1.Person class. Entity class.
a) This class is a table with one to one.
b) he was inside the property with table inside a field (column) is one to one.
c) private property, to have get and set methods. And construction methods.
d) implement the serialization interface.

2.PersonDao class. Dao class
a) a method which five, additions and deletions.
B) Void INSERT (the Person P)
C) Void Delete (int ID)
D) Vodi Update (the Person P)
E) a selectAll List ()
F) between selectOne the Person (int ID)

3.Test class test class
a) method call dao, dao method of testing.

Dao's role:
1. To improve the availability of code
2. Let the individual components function more single, meet single principle functions.

The following is a method of Dao CRUD class:

package jdb

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class PersonDao {
	/*
	 * 到数据库表里面把p插入进去
	 */
	public void insert(Person p){
//		System.out.println(p.getId()+"\t"+p.getName());
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try{
			conn=JdbcUtils.getConnection();
			//3.写sql
			String sql="insert into person values(person_seq.nextval,?,?,?,?)";
			//4.创建ps
			ps=conn.prepareStatement(sql);
			//5.给占位符赋值
			ps.setString(1,p.getName());
			ps.setInt(2,p.getAge());
			ps.setString(3,p.getTel());
			ps.setString(4,p.getAddress());
			//6.执行
			ps.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JdbcUtils.closeAll(conn,ps,rs);
		}
	}
	/**
	 * 根据id把数据库表里面对应的数据删除掉
	 * @param id 要删除的数据的编号
	 */
	public void delete(int id){
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try{
			conn=JdbcUtils.getConnection();
			//3.写sql
			String sql="delete from person where id=?";
			//4.创建ps
			ps=conn.prepareStatement(sql);
			//5.给占位符赋值
			ps.setInt(1,id);
			//6.执行
			ps.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JdbcUtils.closeAll(conn, ps, rs);
		}
	}
	
	public void update(Person p){
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try{
			conn=JdbcUtils.getConnection();
			//3.写sql
			String sql="update person set name=?,age=?,tel=?,address=? where id=?";
			//4.创建ps
			ps=conn.prepareStatement(sql);
			//5.给占位符赋值
			ps.setString(1,p.getName());
			ps.setInt(2,p.getAge());
			ps.setString(3,p.getTel());
			ps.setString(4,p.getAddress());
			ps.setInt(5,p.getId());
			//6.执行
			ps.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JdbcUtils.closeAll(conn,ps,rs);
		}
	}
	
	public Person selectOne(int id){
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		Person p=null;
		try{
			conn=JdbcUtils.getConnection();
			//3.写sql
			String sql="select * from person where id=?";
			//4.创建ps
			ps=conn.prepareStatement(sql);
			//5.执行
			ps.setInt(1, id);
			rs=ps.executeQuery();
			if(rs.next()){
				//获取表中每一个字段的值
				String name=rs.getString("name");
				int age=rs.getInt("age");
				String tel=rs.getString("tel");
				String address=rs.getString("address");
				//把上面这些数据封装到person对象里面
				p=new Person(id,name,age,tel,address);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JdbcUtils.closeAll(conn,ps,rs);
		}	
		return p;
	}
	
	/*
	 * 到数据库里面把所有的person实体查询出来,封装到list集合,然后返回该list集合。
	 */
	public List<Person> selectAll(){
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		List<Person> perList=new ArrayList<Person>();
		try{
			conn=JdbcUtils.getConnection();
			//3.写sql
			String sql="select * from person";
			//4.创建ps
			ps=conn.prepareStatement(sql);
			//5.执行
			rs=ps.executeQuery();
			while(rs.next()){
				//获取表中每一个字段的值
				int id=rs.getInt("id");
				String name=rs.getString("name");
				int age=rs.getInt("age");
				String tel=rs.getString("tel");
				String address=rs.getString("address");
				//把上面这些数据封装到person对象里面
				Person p=new Person(id,name,age,tel,address);
				//把person放入list集合
				perList.add(p);
				
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JdbcUtils.closeAll(conn,ps,rs);
		}		
		return perList;
	}
}

main, Test Test categories:

package jdbc;

import java.util.List;

public class Test {

	public static void main(String[] args) {
		//实例化对象,才能调用该类里面的方法。
		PersonDao pd=new PersonDao();
		/*//调用insert方法时,需要的实参
		Person p=new Person(1,"zhangsan",20,"152226565","郑州市");
		Person p2=new Person("lisi",20,"152226565","郑州市");
		//调用pd对象的insert方法。
		pd.insert(p);*/
//		List<Person> perList=pd.selectAll();
//		for(Person p:perList){
//			System.out.println(p.getName()+"====="+p.getAge());
//		}
//		pd.delete(76);
//		Person p=new Person(77,"wangwu",21,"152226566","郑州市");
//		pd.update(p);
		Person p=pd.selectOne(77);
		System.out.println(p.getName()+"\t"+p.getAge());
	}

}

Problems in the above code:
repeating the method of the CRUD 1.dao class code is very high inside
2. Each method is started to establish a database connection
end 3. Each method is to release resources.
4. We should remove duplicate of the code.
Solution:
extracting two methods dao class.
Connection the getConnection public ();
public void closeAll (Connection Conn, the PreparedStatement PS, the ResultSet RS);
Thus, the method can CRUD code reuse method of the above two.

After the code is improved there are new problems:
1. Late complex project, a project corresponding multiple tables.
2. Multiple tables will have more than dao class
3. Each class requires dao database connection and release resources.
4. Because we have just released the code to establish a connection and resource package to PersonDao. Then the other dao class calling these two methods is very troublesome.

2 JdbcUtils class

To solve the above problem, we can establish a connection and release resources of these two methods to package a common tool class JdbcUtils. This class is all dao class service.
Because getConnection method and closeAll nothing to do with JdbcUtils objects. We put these two methods defined as static methods. Such dao class two when using this method, you can use the class name to call directly, without creating a JdbcUtils objects.
Here Insert Picture Description
Dao class do CRUD operations, JdbcUtils and entity classes to assist dao.

3 using Properties object class which JdbcUtils

While coming out of the two methods allows us to reduce the repetition of the code during development, but now the project is also a problem, is to load drivers and create a database connection are what we write directly to die, but these are likely to be a string constant Modified. In real operating environment is no source. No source can not be changed JdbcUtils class.

So we can put these constants extracted string stored in a file and then read each time data is read from the file, so that you can be a good solution to modify the connection conditions alone.
Here Insert Picture Description
java Jdk there is a class called Properties.
1. he himself is a map collection, you can store data.
2. He has a load (Reader r); method, the method may automatically load the data in the text file.
3. To use the data in a text file, you can call getProperties (String) to obtain data in a text file.

JdbcUtil categories:

package com.macw.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author 超伟
 * @2019年5月28日 下午1:51:58
 * @博客:https://blog.csdn.net/MacWx
 */
public class JdbcUtil {
	public static final Properties prop = new Properties(); 
	//把流操作提取到静态代码块里面。
	static{
		InputStream in = null;
		//使用类加载读取jdbc.properties文件
		in = JdbcUtil.class.getResourceAsStream("/jdbc.properties");
		try {
			//读取文件中的数据
			prop.load(in);
			Class.forName(prop.getProperty("DriverClassName"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally{
			if (in!=null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
	/**
	 * @return Connection
	 */
	public static Connection getConnection(){
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(prop.getProperty("url"),prop.getProperty("username"),prop.getProperty("password"));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return conn;
	}
	
	/**
	 * 
	 * @param conn
	 * @param ps
	 * @param rs
	 */
	public static void toClose(Connection conn,PreparedStatement ps,ResultSet rs){
		try {
			if (rs!=null) {
				rs.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if(ps!=null){
				ps.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if (conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void toClose(Connection conn,PreparedStatement ps){
		try {
			if(ps!=null){
				ps.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if (conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Optimization JdbcUtils class
1. Create a file in src jdbc.properties inside. Right in src - "New-" File-> jdbc.propertis
2. In this file to write key-value pairs, separated by between key =

DriverClassName=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
username=hr
password=mcw

4 database connection pool technology

Why use a database connection pool:
1. establish connections and frequent releases the connection is a waste of resources.
2. Attached Storage can put some up when someone needs to use, you get free connection from the inside
Database connection pool
how to use the database connection pool?
C3P0, DBCP, DRUID, JDNI
DRUID is a database connection pooling Ali realized.
1. Import druid relevant jar package
2. druid string constant internal configuration used to profile properties.
Database connection pool
3. Use in the code database connection pool.
a) create a database connection pool object. (Static code block)
B) obtaining a connection from inside the object database connection pool. (The getConnection ())
C) after use, to return to the pool database connections. (closeAll ())
can refer JdbcUtils tools inside the code.

Guess you like

Origin blog.csdn.net/MacWx/article/details/90666096