Connection pool & mybatis Foundation

Keywords: Mybatis Database Java xml

"Connection pool & mybatis introduction notes"

Learning objectives

  1. Be able to understand the principle of connection pool to solve current problems
  2. Able to use C3P0 connection pool
  3. Ability to use DRUID connection pool
  4. Master the quick start of mybatis framework development

Principle of connection pool to solve current problems

target

  1. Why connection pool is needed
  2. How connection pools work

Manipulate Connection object when JDBC accesses database

Every add, delete, change and query operation of JDBC accessing the database needs to create a connection first, and the connection object cannot be shared. Each user must create a connection object every time they visit, and the connection object should be set as a local variable.

Use of connection objects

  1. After testing, the most time-consuming part of each database access is to create connection objects.
  2. Close the connection object every time you use it.

Two problems need to be solved

  1. How to improve the speed of creating connection objects
  2. How to improve the usage of connected objects

The purpose of using connection pool is to solve the above two problems

Schematic diagram of connection pool

No use of connection pool: each user creates his own connection object when accessing the database

Use connection pool: a certain number of connection objects are created at the beginning of system startup, and can be obtained directly from the connection pool. You do not need to create the connection object yourself.

Summary

Principle of connection pool to solve current problems

Connection object Operating characteristics
When created The connection object is no longer created by itself, but a certain number of connections have been created when the system starts,
And put it in the connection pool
When in use Get a created connection object directly from the connection pool
When closed Instead of actually closing the connection object, put the connection object back in the connection pool for the next user to use

Database connection pool API

target

  1. Interface name of the connection pool
  2. How to get the connection from the connection pool

Data source interface

javax.sql.DataSource Interface

Where is the implementation class? It is implemented by a third-party manufacturer. As long as this interface is implemented, you can write your own connection pool.

Methods in data source interface

Methods in DataSource interface describe
Connection getConnection() Get connection objects from connection pool

Common connection pool parameter meaning

Each connection pool has many parameters. Almost all parameters have default values. We can also adjust them according to the actual situation. Parameter names are different in different connection pools.

Common parameters describe
Number of initial connections Number of connection objects created when the server starts
maximum connection How many connection objects can be allowed in the connection pool at most
Maximum waiting time If there is no connection object in the connection pool, set how long the user waits, in milliseconds.
If this time is exceeded, an exception will be thrown
Maximum idle recycle time If a connection object is not used for a long time, set how long to recycle it. By default, it is not recycled.

Summary

  1. What is the interface name of the connection pool?

    javax.sql.DataSource

  2. What is the way to get connections from the connection pool?

    getConnection()

The introduction of c3p0 connection pool

target

  1. Recognize C3P0 connection pool
  2. Configuration files and classes of c3p0 connection pool

Introduction to common connection pools

DataSource itself is only an interface provided by Oracle company, without specific implementation. Its implementation is implemented by the database manufacturer of connection pool. We just need to learn how to use this tool.

Common connection pool implementation components include:

  1. Alibaba Druid connection pool: Druid is a project on Alibaba's open source platform
  2. DBCP(DataBase Connection Pool) database connection pool is a Java connection pool project on Apache, and also a connection pool component used by Tomcat.
  3. C3P0 is an open source JDBC connection pool. At present, its open source projects include Hibernate, Spring, etc. C3P0 has the function of automatically reclaiming idle connection.

Common configuration properties of C3P0

Even if no parameters are set, each connection pool has default configuration parameters. The following property names will be different for different data source implementation vendors.

Common parameters describe
initialPoolSize Initial number of connections, how many connection objects are created at the beginning
maxPoolSize Maximum connections in connection pool
checkoutTimeout The longest waiting time. How long does it take to get the connection object? Throw an exception
maxIdleTime The longest idle recovery time, not at this time, depends on the usage of the connection pool

Profile requirements

Use the configuration file of c3p0 to configure the connection pool. The configuration file has the following requirements:

  1. File name: must be c3p0-config.xml
  2. Path: this file must be placed in the src directory, that is, under the classpath
  3. There are two configurations
    1. Default configuration: the configuration used by default without specifying a configuration name
    2. Named configuration: multiple configurations can be used, which configuration can be selected by name
    3. Benefits of multiple configurations:
      1. Different connection pool parameters can be used
      2. You can specify different database names, such as: day20, day21
      3. You can specify databases from different vendors, such as Oracle and MySQL

Introduction to API

Class in C3P0

Construction method describe
ComboPooledDataSource() The default construction method, using the default configuration to create a connection pool
Combopooleddatasource (named configuration) Specify which named configuration to use to create the connection pool

Summary

  1. What is the c3p0 connection pool profile name? c3p0-config.xml
  2. What are the classes for creating data sources? ComboPooledDataSource

Case: use C3P0 to create connection pool

demand

  1. Get 10 connection objects from the connection pool and output each object
  2. Set default configuration and naming configuration respectively

Imported packages

Connect to mysql driver and copy to lib directory

step

  1. Import the jar package c3p0-0.9.5.2.jar and mchange-commons-java-0.2.12.jar. If you want to connect to MySQL, you need the database driver: mysql-connector-java-5.1.37-bin.jar
  2. Configure xml
    1. Create configuration file c3p0 in src directory- config.xml , configure corresponding parameters
    2. Set connection parameters of database: user name, password, URL, driver name
    3. Set connection pool configuration parameters: initial number of connections, maximum number of connections, maximum waiting time
  3. Java code
    1. Create the implementation class ComboPooledDataSource of data source, and use the default configuration or named configuration
    2. Get connection objects from connection pool

code

configuration file

<?xml version="1.0" encoding="utf-8"?>
<c3p0-config>
    <!-- Default configuration -->
    <default-config>
        <!--1. Parameters related to database connection. The key is fixed and the value can be modified -->
        <!--mysql Name of driver-->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <!--Connection string URL-->
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/day24</property>
        <!--user name-->
        <property name="user">root</property>
        <!--password-->
        <property name="password">root</property>

        <!--2. Parameters related to connection pool configuration-->
        <!--Number of initial connections-->
        <property name="initialPoolSize">5</property>
        <!--maximum connection-->
        <property name="maxPoolSize">10</property>
        <!--After a long time, the connection was not obtained, and an exception was thrown when the connection timed out-->
        <property name="checkoutTimeout">3000</property>
    </default-config>

    <!--Named configuration, multiple-->
    <named-config name="otherc3p0">
        <!--mysql Name of driver-->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <!--Connection string URL,Modified library name -->
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/day23</property>
        <!--user name-->
        <property name="user">root</property>
        <!--password-->
        <property name="password">root</property>

        <!--Number of initial connections-->
        <property name="initialPoolSize">3</property>
        <!--maximum connection-->
        <property name="maxPoolSize">15</property>
        <!--After a long time, the connection was not obtained, and an exception was thrown when the connection timed out-->
        <property name="checkoutTimeout">2000</property>
    </named-config>
</c3p0-config>

Java code

package com.itheima;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 1. Get 10 connection objects from the connection pool and output each object
 * 2. Set default configuration and naming configuration respectively
 */
public class Demo1C3p0 {

    public static void main(String[] args) throws SQLException {
        //1. Create a connection pool using the default configuration. ComboPooledDataSource implements the DataSource interface
        //ComboPooledDataSource ds = new ComboPooledDataSource();

        //Use named configuration
        ComboPooledDataSource ds = new ComboPooledDataSource("otherc3p0");
        //2. Use the connection pool to get 10 connection objects from the connection pool
        for (int i = 1; i <= 16; i++) {
            Connection connection = ds.getConnection();
            System.out.println("The first" + i + "Connection objects:" + connection);
            //Release 5
            if (i==5) {
                //Put it back in the connection pool
                connection.close();
            }
        }
    }
}

Operation effect

Summary

What are the two configurations of c3p0?

  1. Default configuration
  2. Naming configuration

How to use the above two configurations in Java?

  1. Nonparametric construction method
  2. Parametric construction method

Connection pool using Druid

target

Use druid to create connection pool and get connection object from connection pool

DRUID introduction

Druid is a database connection pool developed by Alibaba called monitoring, which is superior to other database connection pools in function, performance and scalability. Druid has deployed more than 600 applications in Alibaba, which has passed the severe test of large-scale deployment of production environment for more than one year. For example: the annual double 11 event, the annual Spring Festival train tickets.

Druid's download address: https://github.com/alibaba/druid

The jar package used by the DRUID connection pool: druid-1.0.9.jar

Common configuration parameters

parameter explain
url Connection string
username user name
password password
driverClassName The driver class name will be automatically identified according to the URL, which can be unconfigured
initialSize Number of initial connections
maxActive maximum connection
maxWait Maximum waiting time

Introduction to DRUID connection pool API

  1. Get the input stream of the profile
Methods in Class explain
InputStream getResourceAsStream(String path) Load the configuration file under the classpath and convert it to an input stream object
  1. Methods of the Properties class, read all the keys and values in the property file and load them into the collection

  1. Create the connection pool through the static method of druid factory class, and provide the attribute set as the parameter
Method of DruidDataSourceFactory method
public static DataSource createDataSource(Properties properties) Create a connection pool from the properties in the properties collection

Case demonstration

demand

Use druid to create the connection pool, get the connection object from the connection pool, and output the connection object.

Guide bag

step

  1. Create a properties file in the src directory. The file name is optional. Set the above parameters

  2. Java code

    1. Load the contents of the properties file into the properties object
    2. Use the factory class, create the DRUID connection pool, and use the parameters in the configuration file
    3. Take 10 connection outputs from the DRUID connection pool

Imported packages

code

Create a new DRUID configuration file in the src directory, named: druid.properties

url=jdbc:mysql://localhost:3306/test
username=root
password=root
driverClassName=com.mysql.jdbc.Driver
initialSize=5
maxActive=10
maxWait=2000

Java code

package com.itheima;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

public class Demo2Druid {

    public static void main(String[] args) throws Exception {
        //1. Load the configuration file from the classpath to obtain an input stream. If no path is specified, the default is to read the resource file under the same package
        InputStream inputStream = Demo2Druid.class.getResourceAsStream("/druid.properties");
        //2. Use the methods of the Properties object to load the Properties in the configuration file into the Properties object
        Properties properties = new Properties();
        //Loaded all properties in the configuration file
        properties.load(inputStream);
        //3. Create connection pool through druid's factory class
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);

        //Get 10 connection objects
        for (int i = 1; i <= 11; i++) {
            Connection connection = dataSource.getConnection();
            System.out.println("The first" + i + "Connection objects:" + connection);
            //3rd connection closed
            if (i==3) {
                connection.close();
            }
        }
    }
}

effect

Summary

Methods in Class explain
InputStream getResourceAsStream(String path) Read the configuration file in the classpath and return a byte input stream object
Method of DruidDataSourceFactory method
public static DataSource createDataSource(Properties properties) Create a connection pool object through the properties collection of the database

Transforming the tool class of JDBC

demand

Using connection pool to get connection objects to transform JDBC tool class

analysis

Use Druid connection pool to get connection objects and improve the speed of accessing database

  1. Remove the code related to database connection from the class
  2. Get the connection of the database from the connection pool
  3. Add a new method to get the connection pool object
  4. The connection pool (data source) object can be obtained at the beginning of class loading, and the connection pool can be created in the static code block

code

Tool class code

package com.itheima.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.itheima.Demo2Druid;

import javax.sql.DataSource;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * Tool class for accessing database
 * @author newboy
 * @version 3.0
 */
public class JdbcUtils {

    //Declare a connection pool object and use druid to connect to the pool
    private static DataSource dataSource;

    //Create a connection pool when the class is loaded
    static {
        //1. Load the configuration file from the classpath to get an input stream. If no path is specified, the default is to read the resource file under the same package
        try (InputStream inputStream = JdbcUtils.class.getResourceAsStream("/druid.properties")) {
            //2. Use the methods of the Properties object to load the Properties in the configuration file into the Properties object
            Properties properties = new Properties();
            //Loaded all properties in the configuration file
            properties.load(inputStream);
            //3. Create connection pool through druid's factory class
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Get connection pool object
     * @return
     */
    public static DataSource getDataSource() {
        return dataSource;
    }

    /**
     * Get connection to database
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * Close connection
     * Query calls this method
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * Close connection
     * No result set for addition, deletion and modification
     */
    public static void close(Connection connection, Statement statement) {
        //Call the above method directly
        close(connection, statement, null);
    }


    /**
     * General method of adding, deleting and modifying
     * @param sql SQL statement to execute
     * @param params Replace the real address of the placeholder, an array inside the method (starting at 0)
     * @return Rows affected
     */
    public static int update(String sql, Object... params) {
        Connection connection = null;
        PreparedStatement ps = null;

        int row = 0;  //Rows affected
        try {
            //1. Create connection object
            connection = getConnection();
            //2. Create a precompiled statement object
            ps = connection.prepareStatement(sql);
            //2.5 get parameter metadata
            ParameterMetaData metaData = ps.getParameterMetaData();
            int count = metaData.getParameterCount();  //Get several parameters
            //3. Replace placeholders with real values
            for (int i = 0; i < count; i++) {
                ps.setObject(i + 1, params[i]);  //Must be an object type
            }
            //4. Execute SQL statement
            row = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(connection, ps);  //Call your own methods
        }
        return row;
    }

    /**
     * General query method
     * @param sql SQL statement to execute
     * @param clazz The type to instantiate, such as: Student.class, Employee.class
     * @param params Replace the actual value of the placeholder
     * @return Encapsulated collection objects
     */
    public static <T> List<T> query(String sql, Class<T> clazz, Object... params) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;

        List<T> list = new ArrayList<>();
        try {
            //1. Create connection object
            connection = getConnection();
            //2. Create a precompiled statement object
            ps = connection.prepareStatement(sql);
            //2.5 get parameter metadata
            ParameterMetaData metaData = ps.getParameterMetaData();
            int count = metaData.getParameterCount();  //Get several parameters
            //3. Replace placeholders with real values
            for (int i = 0; i < count; i++) {
                ps.setObject(i + 1, params[i]);  //Must be an object type
            }
            //4. Query
            resultSet = ps.executeQuery();
            //5. Traverse the entire result set, encapsulate it into the set, and each element is an object
            while (resultSet.next()) {
                //Each record is encapsulated into an object, and an object is created
                T obj = clazz.getConstructor().newInstance();
                //Get the attributes of entity class first
                Field[] fields = clazz.getDeclaredFields();  //Get all member variables, including private
                //Traverse each member variable to assign a value
                for (Field field : fields) {
                    //Private violence
                    field.setAccessible(true);
                    //Column name = attribute name
                    String name = field.getName();
                    //Object to assign, value
                    field.set(obj, resultSet.getObject(name));   //Get data from result set
                }
                //6. Add to collection
                list.add(obj);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            close(connection, ps, resultSet);
        }
        return list;
    }
}

Use tool class

package com.itheima;

import com.itheima.entity.Student;
import com.itheima.utils.JdbcUtils;

import java.util.List;

/**
 * Use tool class
 */
public class Demo3UseUtils {

    public static void main(String[] args) {
        //Add 1 record with tool class
        int row = JdbcUtils.update("insert into student values(null,?,?,?)", "Chang'e", 0, "1997-07-07");
        System.out.println("Added" + row + "strip");

        //Use tool class to query all data
        List<Student> students = JdbcUtils.query("select * from student", Student.class);
        //Printing
        students.forEach(System.out::println);
    }

}

effect

Summary

Modified the way to get the connection

  1. Create connection pool object in static code block
  2. Added method to get data source
  3. Modified the method of getting the connection to get the connection object from the connection pool

Benefits of framework development

target

  1. What is a framework

  2. What problems does the framework solve

  3. Common framework under layered development

What is a framework

The framework in program development is often the encapsulation of common functions, which is understood as the basis or mechanical standard parts (such as the mechanical parts of screw and nut standards).

If you want to build a carriage, in the case of no frame, you need to cut wood by yourself, to make wood into boards, sticks, then make up wheels, doors, and other parts, and then assemble them.

But if you use a frame, it's equivalent to having wheels, doors and other components ready-made. You just need to assemble them.

A framework is a set of reusable design components.

Framework is the reusable design of the whole or part of the system, and it is the encapsulation of the underlying technology of Java EE.

Framework is an application framework that can be customized by developers.

Framework is a semi-finished product, software is a finished product. We develop finished products based on it.

Problems solved by framework

Solve the problem of general technology

In the Java EE system, there are various technologies. Different software enterprises choose different technologies according to their own business needs, which is easy to cause application dependent technology and increase the complexity and technical risk of project development. The application design and implementation technology should be decoupled in enterprise projects.

Improved development efficiency

Using a framework in an enterprise project, you only need to focus on implementing the business requirements. The convenience of using the framework improves the development efficiency.

Improved system stability

A mature framework has been verified and used in many enterprise projects, and its stability is guaranteed.

Introduction to mybatis framework

target

  1. Introduction to mybatis framework

  2. mybatis framework official website and jar package download

Framework introduction

Mybatis is an open source project under the apache Software Foundation, formerly known as iBatis framework. In 2010, the project was moved from apache Software Foundation to google code and renamed mybatis. Moved to github in November 2013.

Advantages of mybatis

  1. Easy to learn: mybatis itself is small and simple. Without any third-party dependency, the simplest installation is just two jar files + several SQL mapping files.
  2. Flexibility: Mybatis does not impose any impact on the existing design of the application or database. SQL statements are written in XML for unified management and optimization.
  3. Decouple SQL and program code: separate business logic and data access logic by providing DAO layer to make the system design clearer, easier to maintain and easier to unit test. The separation of SQL statement and code improves maintainability.

The shortcomings of mybatis

  1. When writing SQL statements, there is a lot of work, especially when there are many fields and associated tables.
  2. SQL statement depends on the database, which leads to poor portability of the database and cannot be replaced.
  3. The framework is still relatively simple, the function is still missing, and the second level cache mechanism is poor

The concept of ORM

  1. ORM concept: Object Relational Mapping

    java language is object-oriented, mysql is relational database, both need to have a mapping mechanism, this mapping mechanism is called ORM. It's done automatically by the framework.

  2. Two mapping methods of mybatis

    1. Configuration file via XML
    2. By annotation

Official website and framework package download

Official website

website: http://www.mybatis.org/mybatis-3/

Frame package download

Connect to GitHub address: https://github.com/mybatis/mybatis-3/releases

Summary

  1. What is the mybatis framework?

    1. The persistence layer framework, which is used to access the database, is just one of many persistence layer frameworks
    2. ORM framework: Object Relational Mapping Framework
  2. What is ORM?

    Mapping a relational database to an object-oriented programming language, if using a framework, is done by the framework

  3. Which two configurations can the mybatis framework use to map the object relationship between java objects and sql statements?

    1. Through XML configuration file
    2. By annotation

Entry case: Environment Construction

target

  1. The construction of mybatis development environment
    
  2. Understand the development steps of mybatis
    

demand

Query all users from MySQL using mybatis framework

Prepare data

Table to query

create table user (
  id int primary key auto_increment,
  username varchar(20) not null,
  birthday date,
  sex char(1) default 'male',
  address varchar(50)
);

insert into user values (null, 'Sun WuKong','1980-10-24','male','Huaguoshan water curtain cave');
insert into user values (null, 'White bone essence','1992-11-12','female','Baihuling baigudong');
insert into user values (null, 'Zhu Bajie','1983-05-20','male','Yunzhan cave in Fulin mountain');
insert into user values (null, 'spider goblin','1995-03-22','female','Discoid hole');

select * from user;

step

  1. Create project (module)

  2. Create the lib directory and copy the following packages

    1. Logging package

    2. mysql driver

    3. Package of mybatis framework

  3. Core profile: sqlMapConfig.xml Put it in src directory

  4. Logged configuration file: log4j.properties

  5. Write user DAO interface (UserMapper)

  6. Write user DAO interface mapping file( UserMapper.xml )Put in the same directory as DAO interface

  7. Modify the core configuration file sqlMapConfig.xml , loading UserMapper.xml

  8. Write test code

There are two types of mybatis configuration files, both of which are XML files

  1. Core profile: configure database connection, connection pool and other attributes
  2. Entity class mapping file: write SQL statements to specify the mapping relationship between tables and ORM classes

Project structure

[failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-oiVhV4Po-1592716080793)(assets/1562393860427.png))

log4j.properties

Copy to src directory, and sqlMapConfig.xml Core profiles together

Role: profile of the logging component of mybatis

User entity class

Packaging:

package com.itheima.entity;

import java.sql.Date;

/**
 User entity class object */
public class User {
	  //The basic type uses a wrapper class. The advantages of using a wrapper class are more consistent with the table. For example, this column in the table is null, int is 0 by default, and integer is not null
    private Integer id;  
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    public User() {
    }

    public User(Integer id, String username, Date birthday, String sex, String address) {
        this.id = id;
        this.username = username;
        this.birthday = birthday;
        this.sex = sex;
        this.address = address;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

Getting started case: profiles and interfaces

target

  1. Preparation of core configuration file
  2. Compilation of entity class mapping file

Core profile: sqlMapConfig.xml

Core configuration file in src directory

  • You can find the configuration template in getting started on mybatis official website:

    http://www.mybatis.org/mybatis-3/zh/getting-started.html

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--1. Configure connection pool parameters-->
            <dataSource type="POOLED">
                <!--Database driver class name-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--Connection string-->
                <property name="url" value="jdbc:mysql://localhost:3306/day24"/>
                <!--user name-->
                <property name="username" value="root"/>
                <!--password-->
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--2. Specify the location of the entity class mapping file. This is not the package name, but the path -->
        <mapper resource="com/itheima/dao/UserMapper.xml"/>
    </mappers>
</configuration>
  • Templates can be defined in idea and reused later.

Creation of UserMapper interface

It is the method in DAO interface:

  • How to query all users
package com.itheima.dao;

import com.itheima.entity.User;

import java.util.List;

/**
 * DAO Layer interface
 */
public interface UserMapper {

    /**
     * Query all users
     */
    List<User> findAllUsers();
}

Entity mapping file: UserMapper.xml

effect:

  1. Writing SQL statements
  2. Specify ORM mapping, class property name and table field mapping relationship

Create com/itheima/dao and create it in the directory UserMapper.xml Mapping files

Templates for mapping files can be found in the http://www.mybatis.org/mybatis-3/zh/getting-started.html Found.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace: Namespace, specifies the fully qualified name of the interface-->
<mapper namespace="com.itheima.dao.UserMapper">
    <!--
    id: Represents the method name in the interface
    resultType: Represents the data type returned by the method. If the returned data is a collection, the type of each element in the collection is specified here
    select The label body is SQL sentence
    -->
    <select id="findAllUsers" resultType="com.itheima.entity.User">
        select * from user
    </select>
</mapper>

Core profile sqlMapConfig.xml

add to UserMapper.xml Mapping of

<mappers>
    <! -- 2. Specify the location of entity class mapping file. This is not the package name, but the path -- >
    <mapper resource="com/itheima/dao/UserMapper.xml"/>
</mappers>

Summary

  1. What are the two profiles in mybatis?
    1. Core profile:
      1. Configure connection pool information
      2. Load entity class mapping file
    2. Entity class mapping file:
      1. Writing SQL statements
      2. Specify the mapping relationship between entity class and table column name
  2. UserMapper.xml The function of each parameter in the configuration file
Property name effect
namespace Specifies the fully qualified name of the interface
id Name of method in interface
resultType Specifies the data type returned by the method, and if it is a collection type, specifies the type of each element in the collection
Tagging body SQL statement

Entry case: test class

target

  1. Core objects in mybaits
  2. Write Java code for mybatis to access database

Three object functions and life cycle

  1. Sqlsessionfactorybuilder (manufacturer's worker): a session factory creation class, which is used to create a session factory. It can be instantiated directly at the first run.
  2. Sqlsessionfactory (factory): the session factory class is a heavyweight object. You only need to create one in each project.
  3. Sqlsession (car): every time a user accesses the database, a session object will be created. This object cannot be shared. Each user has its own session object. It is created by the factory object above. Session objects are lightweight objects that can be created every time they are accessed and closed when they are used up. Similar to Connection connection object.

Writing process

step

  1. Through the Resources class provided by the framework, load sqlMapConfig.xml , get the file input stream InputStream object

  2. Instantiate session factory create class SqlSessionFactoryBuilder

  3. Through the above SqlSessionFactoryBuilder object, read the input stream of the core configuration file, and get the session factory SqlSessionFactory class

  4. Create a SqlSession object using the SqlSessionFactory object

    1. It is equivalent to the Connection object in JDBC and provides CRUD method for operating database
    2. It provides a getMapper() method to get the implementation object of the interface.
  5. Get the interface object UserMapper, get the interface proxy object

  6. Perform database query operation and output user information

  7. Close the session and free up resources.

Test code

package com.itheima.test;

import com.itheima.dao.UserMapper;
import com.itheima.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Write test class
 */
public class TestUserMapper {

    public static void main(String[] args) throws IOException {
        //Mybatis also provides a tool class to read the configuration file in the src directory directly and convert it into an input stream. Note: do not misdirect the package
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        //1. Create session factory construction class
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //2. Create session factory object and read core configuration file
        SqlSessionFactory factory = builder.build(inputStream);
        //3. Get the session object from the factory, which is equivalent to getting the connection object of the database
        SqlSession sqlSession = factory.openSession();
        //4. Get the proxy object of DAO, which is the implementation class of DAO. Polymorphism, the interface in front and its implementation class in the back
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //5. Call the method in DAO interface to add, delete, modify and query
        List<User> users = userMapper.findAllUsers();
        //6. Output query results
        users.forEach(System.out::println);
        //7. Release resources
        sqlSession.close();
    }

}

Note: the object of UserMapper is the interface proxy object generated by mybatis

Summary

  1. Read core profile input stream
  2. Create factory build class - > create session factory class - > session class
  3. Get the implementation class of the interface through getMapper() of the session object
  4. Add, delete, modify and query methods in the calling interface
  5. Close session

Learning summary

  1. Be able to understand the principle of connection pool to solve current problems

Connecting objects Operating characteristics
When created A certain number of connection objects are created from the beginning of the connection pool. You do not need to create connection objects yourself
When in use Get a created connection object directly from the connection pool
When closed Instead of actually closing the connection object, it puts it back into the connection pool
  1. Able to use C3P0 connection pool

    1. Configure c3p0-config.xml In src directory
    2. Specify connection database information and connection pool information in the configuration file
    3. Creating connection pools using ComboPooledDataSource
      1. Nonparametric construction method is the default configuration
      2. The construction method with parameters is named configuration
  2. Ability to use DRUID connection pool

    1. Create a configuration file with the extension. properties
    2. Read the configuration file to get the input stream object
    3. Load the configuration using the load() method of the Properties class
    4. Create the connection pool through Druid's factory class: createDataSource(). Dr uidDataSourceFactory.createDataSource ()
  3. Master the quick start of mybatis framework development

    1. Create project

    2. Create the lib directory and copy the following packages

      1. Logging package
      2. mysql driver
      3. Package of mybatis framework
    3. Core profile: sqlMapConfig.xml Put it in src directory

    4. The configuration file for logging: log4j.properties is placed in the src directory

    5. Write user DAO interface (UserMapper)

    6. Write user DAO interface mapping file( UserMapper.xml )

    7. Modify the core configuration file sqlMapConfig.xml , loading UserMapper.xml

    8. Write test code

      |

Posted by spires on Sun, 21 Jun 2020 00:12:55 -0700