Nine, MySQL 09 data access and DAO mode

9. Data Access and DAO Patterns

9.1 Properties configuration file

9.1.1 Introduction to Properties configuration file

  • There is a more important Properties class in Java, which can read Java configuration files
  • Commonly used configuration information can be written in the configuration file, which is convenient for software engineers to maintain and modify
  • That is, the server parameters used to operate the database can be written into the configuration file
  • A Java configuration file is usually a file with the extension .properties
  • Data is stored in the file in the format of "key=value"
  • Comments can be added using "#"
  • The configuration file added for database access will be named datebase.properties

9.1.2 Steps to use the Properties configuration file

1. Add properties file

  • Select the src file under the project and right-click, and execute the "New-File" command in the pop-up shortcut menu
  • Then open the "New File" to create a file with the suffix properties

2. Edit configuration file

  • Add configuration information in the database.properties file

  • When connecting to the database, the parts that may be modified are the database driver (driver), database connection URL (url),

    Username (user) and password (password) to connect to the database

  • Fill in the configuration file according to the Properties file format, as follows

dirver=com.mysql.jdbc.Driver;
url=jdbc:mysql://localhost:3306/hospital?useUnicode=ture&characterEncoding=UTF-8
user=root
password=root
  • The data format in the configuration file is similar to the Map structure in Java. Before the equal sign is the key, and after the equal sign is the
  • In the configuration file, the key should be unique, but the value can not be unique

3. Read configuration information

  • Use the Properties class under the java.util package to read configuration files, and the Properties class inherits from the Hashtable class
  • Common methods of the Properties class
methoddescribe
String getProperty(String key)Use the specified key to search for an attribute in this attribute list, and get its corresponding value through the parameter key
Object serProperty(String key,String value)Set key-value pairs by calling the put() method of the base class Hashtable
void load(InputStream inStream)Read the attribute list (key and element pair) from the input stream, obtained by loading the specified file
All key-value pairs in this file
void clear()Clear the loaded key-value pairs, this method is provided by the base class Hashtable

9.1.3 Use the Properties configuration file to configure the parameters of the file

  • Write a DBUtil tool class to facilitate future database connections
  • Write the inti() method to configure the parameters for connecting to the database
public class DBUtil {
    public static String driver;
    public static String url;
    public static String user;
    public static String password;
    //Static method, automatically called when the class is created
    static{
        init();
    }
    //configuration file
    public static void init(){
        String file="database.properties";
        InputStream in=DBUtil.class.getClassLoader().getResourceAsStream(file);
        Properties ties=new Properties();
        try {
            ties.load(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        driver= ties.getProperty("driver");
        url=ties.getProperty("url");
        user=ties.getProperty("user");
        password=ties.getProperty("password");
    }
  • When connecting to the database again, you don’t need to configure parameters such as driver, just call the static variables of this class directly

9.2 DAO pattern

9.2.1 DAO pattern concept

  • DAO (Data Access Object) data access object. The main function is for data manipulation, which belongs to the data layer operation in the standard development framework of the program
  • Easy to switch between different databases
  • There are three main players in the DAO model
    • Data Access Object Interface: Defines the standard operations to be performed on a model object
    • Data access object entity class: implements the data access object interface and is responsible for obtaining data from storage mechanisms such as databases
    • Model object/value object: a class object used to store the obtained data
  • UML diagram of DAO pattern
  • In the figure above, Student is a model object/value object (entity class)
  • StudentDao is a data access object interface, which specifies what operations should be performed on the data of the student type
  • StudentDaoImpl is the role of the data access object entity class, which specifically implements how to obtain data from the database to perform these operations of adding, deleting, modifying and checking

9.2.2 Entity classes

  • Entity (entity class) is the class corresponding to the data table in the Java project

  • Entity Class Features

    • Attributes are generally modified with private
    • Provide public modified getter/setter methods
    • The entity class provides a parameterless construction method, and provides a parameterized construction method according to the business
    • Implement the java.io.Serializable interface and support the serialization mechanism, which can convert the object into a byte sequence and save it on disk or transmit it on the network
  • When operating the database, the entities and relationships in the database will be organized in the form of entity classes

  • Usually in a Java project, create a Package collection named entity to save the entity class

  • example

The following tables are the fields in the patient table, and the patient entity is constructed. The attributes in the entity class correspond to the fields in the patient table

nametypelengthdecimal pointnot nullvirtualkeynote
patientIDint40primary keypatient number
passwordvarchar200login password
birthDatedate00date of birth
gendervarchar40gender
patirentNamevarchar500patient name
phoneNumvarchar500contact number
emailvarchar700Mail
identityNumvarchar200ID number
addressvarchar2550address

Construct the entity class of the patient table in the Java project

package cn.QiaoYun.entity;

/*
 * patient form
 * */
public class Patient {

  private int patientId;
  private String password;
  private String birthDate;
  private String gender;
  private String patientName;
  private String phoneNum;
  private String email;
  private String identityNum;
  private String address;

  public int getPatientId() {
    return patientId;
  }

  public void setPatientId(int patientId) {
    this.patientId = patientId;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getBirthDate() {
    return birthDate;
  }

  public void setBirthDate(String 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;
  }

  public Patient() {
  }

  public Patient(int patientId, String password, String 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;
  }

  @Override
  public String toString() {
    return "Patient{" +
            "patientId=" + patientId +
            ", password='" + password + '\'' +
            ", birthDate='" + birthDate + '\'' +
            ", gender='" + gender + '\'' +
            ", patientName='" + patientName + '\'' +
            ", phoneNum='" + phoneNum + '\'' +
            ", email='" + email + '\'' +
            ", identityNum='" + identityNum + '\'' +
            ", address='" + address + '\'' +
            '}';
  }
}

9.2.3 Implementing the DAO pattern

  • When implementing the DAO mode, it is first necessary to define a unified abstract API, and abstract the code for operating data into an interface, and only need to call these codes to realize access to data
  • After the interface is created, a new interface implementation class is usually created. Considering the differences in the implementation codes of different databases, the implementation class can be defined as follows
  • When writing the implementation class, each operation needs to be connected to the database. These operations of connecting to the database can be written into a class and placed in a special class ---- BaseDao
  • At the same time, you can also write a general operation of adding, deleting, and modifying in BaseDao. When you need to operate, just pass in different parameters

9.2.4 DAO model summary

  • The advantage of the DAO pattern is that it achieves two isolations
    • Data access code and business logic code are isolated, that is, code coupling
    • The implementation of different databases is isolated.
  • Main parts of a typical DAO pattern
    • Entity class: used to store transfer object data
    • Database operation tool class: the BaseDao class, which avoids the repeated use of database connection and shutdown codes, and facilitates modification
    • DAO interface: define abstract methods for all operations on the database, and can provide multiple implementations
    • DAO implementation class: give specific implementations of DAO interface definition methods for different databases

9.3 Project package naming convention

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-Z69HuFkU-1679566464725)(assets/%E9%A1%B9%E7%9B%AE%E5%8C% 85%E5%91%BD%E5%90%8D%E8%A7%84%E8%8C%83.png)]

9.2.4 DAO model summary

  • The advantage of the DAO pattern is that it achieves two isolations
    • Data access code and business logic code are isolated, that is, code coupling
    • The implementation of different databases is isolated.
  • Main parts of a typical DAO pattern
    • Entity class: used to store transfer object data
    • Database operation tool class: the BaseDao class, which avoids the repeated use of database connection and shutdown codes, and facilitates modification
    • DAO interface: define abstract methods for all operations on the database, and can provide multiple implementations
    • DAO implementation class: give specific implementations of DAO interface definition methods for different databases

9.3 Project package naming convention

Tags: Database MySQL Java

Posted by strudo on Fri, 24 Mar 2023 17:22:27 +0530