当前位置:网站首页>JDBC MySQL 02 data access and Dao mode
JDBC MySQL 02 data access and Dao mode
2022-07-27 18:54:00 【A sea of clouds, a first thought】
Data access and DAO Pattern
List of articles
- Data access and DAO Pattern
List of articles
- Data access and DAO Pattern
One 、 Learning goals
- master DAO Pattern
- master Properties How to use the configuration file
Two 、 Data persistence
2.1 Data persistence concept
- The mechanism of transforming the data in the program between the transient state and the persistent state is Data persistence
2.2 Implementation of persistence
- database
- Ordinary documents
- XML file
3、 ... and 、 Why JDBC encapsulation
What are the disadvantages of the following code ?
package com.aiden.jdbc; import java.sql.*; import java.util.Scanner; /** * @author Aiden */ public class UserLogin { public static void main(String[] args) { // Business operation tips Scanner input=new Scanner(System.in); System.out.println(" Please enter a user name :"); String userName=input.next();// user name System.out.println(" Please input a password :"); String userPwd=input.next();// password // Access database boolean isLogin = login(userName, userPwd); // Business operation judgment if(isLogin){ System.out.println(" Login successful "); }else{ System.out.println(" Login failed ! Wrong username and password "); } } // Login authentication method public static boolean login(String userName,String userPwd){ boolean isLogin=false; // Access database Connection conn =null; PreparedStatement stmt=null; ResultSet rs=null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t147hospital?serverTimeZone=UTC","root","root"); //1.sql sentence String sql="select * from user where userName=? and userPwd=?"; //2. Instantiate the execution object prepareStatement stmt=conn.prepareStatement(sql); //3. Set parameters stmt.setObject(1,userName); stmt.setObject(2,userPwd); //4. Call the execution method rs=stmt.executeQuery(); if (rs!=null&&rs.next()){ isLogin=true; }else{ isLogin=false; } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { // close resource try { if(rs!=null){ rs.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if(stmt!=null){ stmt.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if(conn!=null){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } return isLogin; } }Existing problems :
Solution :
Interface oriented programming is adopted , Can reduce the coupling between the code
Advantages of interface oriented programming :
- Isolate business logic code and data access code
- Isolate the implementation of different databases
Four 、JDBC Preliminary packaging implementation of
analysis :
- General data access operations :
- Establishment and closing of database connection
- increase 、 Delete 、 Change Check method
- Whether the code can be further optimized ???
Solution :
- General operation ( open 、 Close connections, etc ) Encapsulate to tool class
BaseDaoBaseDao Wrapper class
The name of the package : A lowercase letter com.hospital.daopackage com.hospital.dao; import java.sql.*; /** * Database access tool class * * @author Aiden */ public class BaseDao { private String driver = "com.mysql.cj.jdbc.Driver"; private String url = "jdbc:mysql://localhost:3306/t147hospital?serverTimezone=Asia/Shanghai"; private String user = "root"; private String password = "root"; protected Connection conn;// Connection object /** * Establishing a connection * * @return */ public Connection getConnection() { try { // The load driver Class.forName(driver); // Establishing a connection conn = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return conn; } /** * close resource * * @param conn Connection object * @param stmt Perform object * @param rs Result set */ public void closeAll(Connection conn, Statement stmt, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * increase Delete Change Method * No arguments :int result=executeUpdate(sql); * Ginseng :int result=executeUpdate(sql,id); * Ginseng :int result=executeUpdate(sql,name,age,sex); * * @param sql Executes sql command * @param params Parameters ( Optional parameters ) * @return Rows affected int type * @throws SQLException */ public int executeUpdate(String sql, Object... params) throws SQLException { int result = 0; // Declare the execution object PreparedStatement stmt = null; try { // Establishing a connection this.conn = getConnection(); // Instantiate the execution object stmt = conn.prepareStatement(sql); // If there are parameters, set the parameters if (params != null && params.length > 0) { // Loop setting parameters for (int i = 0; i < params.length; i++) { stmt.setObject((i + 1), params[i]); } } // Start execution result = stmt.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(" Exception accessing database !", e); } finally { // close resource this.closeAll(conn, stmt, null); } return result; } /** * Query methods * ( Resources need to be released manually ) * No arguments :ResultSet rs=executeQuery(sql); * Ginseng :ResultSet rs=executeQuery(sql,name); * Ginseng :ResultSet rs=executeQuery(sql,name,sex); * * @param sql Executes sql command * @param params Parameters ( Optional parameters ) * @return ResultSet Result set object * @throws SQLException */ public ResultSet executeQuery(String sql, Object... params) throws SQLException { // Result set ResultSet rs = null; // Declare the execution object PreparedStatement stmt = null; try { // Establishing a connection this.conn = getConnection(); // Instantiate the execution object stmt = conn.prepareStatement(sql); // If there are parameters, set the parameters if (params != null && params.length > 0) { // Loop setting parameters for (int i = 0; i < params.length; i++) { stmt.setObject((i + 1), params[i]); } } // Execute query request rs = stmt.executeQuery(); } catch (SQLException e) { throw new RuntimeException(" Exception accessing database !", e); } return rs; } }Test call
- Data table structure
drop database if exists `t147hospital`; # Chuang Ku create database if not exists t147hospital; use t147hospital; drop table if exists `user`; # Table creation create table `user`( `userId` int(0) not null auto_increment comment ' Primary key number ', `userName` varchar(50) not null comment ' user name ', `userPwd` varchar(50) not null comment ' password ', primary key (`userId`) using btree ) ; # Insert simulation data insert into `user` values (1, 'admin', '123456'); insert into `user` values (2, 't147', '123456');
- Test code
package com.hospital.test; import com.hospital.dao.BaseDao; import java.sql.SQLException; /** * @author Aiden */ public class TestJDBCBaseDao extends BaseDao { // test BaseDao Methods of addition, deletion and modification public static void main(String[] args) { TestJDBCBaseDao dao=new TestJDBCBaseDao(); if (dao.delete()) { System.out.println(" Successful operation !"); }else{ System.out.println(" operation failed !!!"); } } // Test new public boolean insert() { int result = 0; String sql = "insert into `user` (userName,userPwd) values(?,?);"; try { result = executeUpdate(sql, "aiden", "123456"); } catch (SQLException e) { e.printStackTrace(); } return result > 0; } // Test modification public boolean update() { int result = 0; String sql = "update user set userPwd=? where userId=?;"; try { result = executeUpdate(sql, "666666",3); } catch (SQLException e) { e.printStackTrace(); } return result > 0; } // Test to delete public boolean delete() { int result = 0; String sql = "delete from user where userId=?;"; try { result = executeUpdate(sql, 3); } catch (SQLException e) { e.printStackTrace(); } return result > 0; } }
5、 ... and 、 What is? DAO?
Very popular data access patterns ——DAO Pattern
Data Access Object( Data access object )
Between business logic and persistent data
Achieve access to persistent data
5、 ... and 、DAO The composition and introduction of the mode
5.1 Part of the
Database tool class BaseDao => be located
daoIt's a bagEntity class => be located
entityIt's a bagDAO Interface => be located
daoIt's a bagDAO Implementation class => be located
dao.implIt's a bag
5.2 Entity class (entity)
- Entity class (Entity) yes Java The class corresponding to the database table in the application
- For storing data , And provide access to these data
- Usually , Implementation classes are persistent , Need to be stored in a file or database
- When accessing the operation database , Organize entities and relationships in the database in the form of entity classes
- Usually , stay Java Create a project named entity Of Package, Used to save entity classes
- A database table corresponds to an entity class
- Entity class features
- Properties are generally used
privatemodification- Provide public Embellished
getter/setterMethod- Entity classes provide parameterless construction methods , According to the business, provide a parameter structure
- Realization
java.io.SerializableInterface , Support serialization mechanism , This object can be converted into a sequence of bytes and stored on disk or transmitted over the network- If the entity class implements
java.io.SerializableInterface , Attributes should be definedserialVersionUID, Solve the serialization problem between different versions- by
serialVersionUIDThe method of assignment- Once it is an entity class serialVersionUID assignment , Just don't modify ; otherwise , When deserializing data from previous versions , Will be submitted to the java.io.InvalidClassException abnormal
5.3 Defining entity classes
package com.hospital.entity; import java.io.Serializable; import java.util.Date; /** * Patient information entity class */ public class Patient implements Serializable { // Defining attributes serialVersionUID, Solve the serialization problem between different versions private static final long serialVersionUID = -6418684824125291382L; // Properties are generally used `private` modification private Integer patientId;// Patient number private String password;// password private Date birthDate;// Date of birth private String gender;// Gender private String patientName;// full name private String phoneNum;// mobile phone private String email;// mailbox private String identityNum;// Id card private String address;// Contact address // No arguments structure public Patient() { } // There are parametric structures public Patient(Integer patientId, String password, Date birthDate, String gender, String patientName, String phoneNum, String email, String identityNum, String address) { this.patientId = patientId; this.password = password; this.birthDate = birthDate; this.gender = gender; this.patientName = patientName; this.phoneNum = phoneNum; this.email = email; this.identityNum = identityNum; this.address = address; } //getter/setter Method public Integer getPatientId() { return patientId; } public void setPatientId(Integer patientId) { this.patientId = patientId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getPatientName() { return patientName; } public void setPatientName(String patientName) { this.patientName = patientName; } public String getPhoneNum() { return phoneNum; } public void setPhoneNum(String phoneNum) { this.phoneNum = phoneNum; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getIdentityNum() { return identityNum; } public void setIdentityNum(String identityNum) { this.identityNum = identityNum; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }5.4 Use entity classes to pass data
@Override public List<Patient> findAll() throws SQLException { String sql = "select patientId,patientName,gender,birthDate,email from patient"; List<Patient> list = new ArrayList<>(); // Execute query request , And save the query to the result set ResultSet in ResultSet rs = this.executeQuery(sql); // Loop out the data in the result set , And add to the generic collection List in , In this way, we can use entity classes to transfer data while (rs.next()) { Patient patient = new Patient(); patient.setPatientId(rs.getInt("patientId")); patient.setPatientName(rs.getString("patientName")); patient.setGender(rs.getString("gender")); patient.setBirthDate(rs.getDate("birthDate")); patient.setEmail(rs.getString("email")); list.add(patient);// Loop add data } // close resource this.closeAll(conn, null, rs); // Return the set data finally obtained from the result set return list; }5.5Dao Interface
package com.hospital.dao; import com.hospital.entity.Patient; import java.sql.SQLException; import java.util.List; /** * Patient DAO Interface * * @author Aiden */ public interface PatientDao { /** * Query multiple data * * @return */ List<Patient> findAll() throws SQLException; /** * Fuzzy query based on patient name * * @param patientName Patient's name * @return */ List<Patient> findByPatientName(String patientName) throws SQLException; /** * Query single object * * @param patientId * @return */ Patient findById(Integer patientId) throws SQLException; /** * newly added * * @param patient Patient object * @return */ int insert(Patient patient) throws SQLException; /** * modify * * @param patient Patient object * @return */ int update(Patient patient) throws SQLException; /** * Delete * * @param patientId Patient number * @return */ int delete(Integer patientId) throws SQLException; }5.6Dao Realization
package com.hospital.dao.impl; import com.hospital.dao.BaseDao; import com.hospital.dao.PatientDao; import com.hospital.entity.Patient; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Dao Interface implementation class * * @author Aiden */ public class PatientDaoImpl extends BaseDao implements PatientDao { @Override public List<Patient> findAll() throws SQLException { String sql = "select patientId,patientName,gender,birthDate,email from patient"; List<Patient> list = new ArrayList<>(); // Execute query request , And save the query to the result set ResultSet in ResultSet rs = this.executeQuery(sql); // Loop out the data in the result set , And add to the generic collection List in , In this way, we can use entity classes to transfer data while (rs.next()) { Patient patient = new Patient(); patient.setPatientId(rs.getInt("patientId")); patient.setPatientName(rs.getString("patientName")); patient.setGender(rs.getString("gender")); patient.setBirthDate(rs.getDate("birthDate")); patient.setEmail(rs.getString("email")); list.add(patient);// Loop add data } // close resource this.closeAll(conn, null, rs); return list; } @Override public List<Patient> findByPatientName(String patientName) throws SQLException { String sql = "select patientId,patientName,gender,birthDate,email from patient where patientName like CONCAT('%',?,'%')"; List<Patient> list = new ArrayList<>(); // Execute query request , And save the query to the result set ResultSet in ResultSet rs = this.executeQuery(sql, patientName); // Loop out the data in the result set , And add to the generic collection List in , In this way, we can use entity classes to transfer data while (rs.next()) { Patient patient = new Patient(); patient.setPatientId(rs.getInt("patientId")); patient.setPatientName(rs.getString("patientName")); patient.setGender(rs.getString("gender")); patient.setBirthDate(rs.getDate("birthDate")); patient.setEmail(rs.getString("email")); list.add(patient);// Loop add data } // close resource this.closeAll(conn, null, rs); return list; } @Override public Patient findById(Integer patientId) throws SQLException { String sql = "select patientId,patientName,gender,birthDate,email from patient where patientId =?"; Patient patient = null; ResultSet rs = this.executeQuery(sql, patientId); // Determine whether there is data , If any, take it out and store it in Patient The entity class , In this way, we can use entity classes to transfer data if (rs.next()) { patient = new Patient(); patient.setPatientId(rs.getInt("patientId")); patient.setPatientName(rs.getString("patientName")); patient.setGender(rs.getString("gender")); patient.setBirthDate(rs.getDate("birthDate")); patient.setEmail(rs.getString("email")); } // close resource this.closeAll(conn, null, rs); return patient; } @Override public int insert(Patient patient) throws SQLException { String sql = "INSERT INTO `patient`(`password`, `birthDate`, `gender`, `patientName`, `phoneNum`, `email`, `identityNum`, `address`) VALUES (?,?,?,?,?,?,?,?)"; return this.executeUpdate(sql, patient.getPassword(), patient.getBirthDate(), patient.getGender(), patient.getPatientName(), patient.getPhoneNum(), patient.getEmail(), patient.getIdentityNum(), patient.getAddress()); } @Override public int update(Patient patient) throws SQLException { return 0; } @Override public int delete(Integer patientId) throws SQLException { String sql = "delete from patient where patientId=?"; return this.executeUpdate(sql, patientId); } }
6、 ... and 、Properties class
6.0 Why use Properties class
Use JDBC The key code of technology accessing database data
- The following code is not difficult to find , When our database password is modified , At this point we java The source code should also be revised and compiled !
- In the real project development deployment , We often use the information that often changes in the program as The configuration file Storage , Let the user change the relevant variable settings away from the program itself , There is no need to revise java Source code , Omit the compilation and deployment process , It also makes good use of the scalability of the program .
package com.hospital.dao; import java.sql.*; /** * Database access tool class */ public class BaseDao { private String driver = "com.mysql.cj.jdbc.Driver"; private String url = "jdbc:mysql://localhost:3306/t147hospital?serverTimezone=Asia/Shanghai"; private String user = "root"; private String password = "root"; protected Connection conn;// Connection object public Connection getConnection() { try { Class.forName(driver); // The load driver conn = DriverManager.getConnection(url, user, password);// Establishing a connection } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return conn; } }6.1 Advantages of using profiles
- Java The configuration file in is often
xxx.propertiesfile- The suffix is
.properties- The format is
“ key = value ”Format- Use
“#”To comment- Usually , The configuration file added for database access is
database.properties
6.2 establish database.properties file
#MySql8.0 drive jdbc.driver=com.mysql.cj.jdbc.Driver #MySql8.0 Database connection address information ( Including mainframe localhost、 port 3306、 database t147hospital、 Enable Unicode Character set useUnicode=true、 The character is encoded as characterEncoding=utf8、 Do not use when communicating with the server SSL、 The time zone =Asia/Shanghai Wait for settings ) jdbc.url=jdbc:mysql://localhost:3306/t147hospital?allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai #MySql8.0 Database user name jdbc.username=root #MySql8.0 Database password jdbc.password=root6.2Properties Class to read the configuration
Java Provided in Properties Class to read the configuration file
Method name say bright String getProperty(String key)Searches for properties in this property list with the specified key . Through parameters key Get its corresponding value Object setProperty(String key,String value)call Hashtable Methods put. By calling the... Of the base class put() Method to set the key - It's worth it void load(InputStream inStream)Read the list of properties from the input stream ( Bond and element pair ). Get all the keys in the specified file by loading it - It's worth it void clear() Clear the loaded keys - It's worth it , The method consists of a base class Hashtable Provide establish ConfigManager class
package com.hospital.utils; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Configuration file operation tool class * * @author Aiden */ public class ConfigManager { private static Properties properties = null; static { InputStream inputStream = null; inputStream = ConfigManager.class.getClassLoader().getResourceAsStream("database.properties"); if (inputStream == null) { throw new RuntimeException(" Can't find database.properties Database parameter profile !"); } // Instantiation Properties object properties = new Properties(); // Read the list of properties from the input stream try { properties.load(inputStream); } catch (IOException e) { throw new RuntimeException(" Error loading database configuration parameters !", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * according to key obtain properties In the document value value * @param key * @return */ public static String getProperty(String key) { return properties.getProperty(key); } }reform BaseDao
public class BaseDao { // Use ConfigManager The tool class reads the information of the configuration file ( Be careful key Be consistent , Otherwise, the value cannot be read ) private String driver = ConfigManager.getProperty("jdbc.driver"); private String url = ConfigManager.getProperty("jdbc.url"); private String user = ConfigManager.getProperty("jdbc.username"); private String password = ConfigManager.getProperty("jdbc.password"); protected Connection conn;// Connection object public Connection getConnection() { try { // The load driver Class.forName(driver); // Establishing a connection conn = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return conn; } }6.3 Precautions when reading configuration
7、 ... and 、 Summary of this chapter
边栏推荐
- LeetCode 刷题 第三天
- 多功能无线遥控艾灸仪芯片-DLTAP703SD
- org.gradle.api. UncheckedIOException: Could not load properties for module ‘gradle-kotlin-dsl‘ from C
- 图文结合,完美解释MySQL逻辑备份的实现流程
- 商品推荐和分类商品推荐
- LED带风扇护眼学习台灯触摸芯片-DLT8S12A
- TypeScript安装
- Use mobaxtermto establish a two-tier springboard connection
- Aircraft collision detection
- 飞机大战敌机出场
猜你喜欢
随机推荐
EN 1155 building hardware swing door opener - CE certification
订单的提交
Log4j epic loopholes, big companies like jd.com have been recruited
What should I do if MySQL master-slave replication data is inconsistent?
MySQL basic statement
Order timeout cancellation and commodity query by category
Talking about JVM (frequent interview)
Electric heating neck pillow chip-dltap703sc
个人中心--订单业务流程
多功能无线遥控艾灸仪芯片-DLTAP703SD
Led with fan eye protection learning table lamp touch chip-dlt8s12a
LeetCode 刷题 第三天
LeetCode 刷题 第二天
Matplotlib(基本用法)
Was not registered for synchronization because synchronization is not active[resolved]
Uni app for wechat login (to be finished)
Idea 2020.1 Community Edition download experience
Typeerror: conv2d(): argument 'padding' (position 5) must be multiple of ints, not STR [error]
C basic concepts list description suggestions collection
"MySQL things" explains the indexing principle in detail

















