MyBatis basic and configuration

### 1.1. Function

Simplify database programming.

When using MyBatis, you only need to specify the interface and abstract method for operating data, such as adding `void insert (User user)`, and then configure the SQL statement corresponding to this method, you do n’t need to write the implementation class of the interface There is no need to rewrite this abstract method through techniques such as JDBC.

### 1.2. Development steps

#### 1.2.1. Creating a project

Create Maven Project, Group Id is `cn.edu.siso.mybatis`, Artifact Id is` MYBATIS-01-SAMPLE`, Packaging selects `war`, the subsequent steps are the same as the previous project.

** Dependencies in the preamble, web.xml configuration, Spring configuration, and Tomcat running environment are all unnecessary for using MyBatis alone **

#### 1.2.2. Add MyBatis dependencies

Regarding the dependence of MyBatis:

    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>

The MyBatis framework can be used independently, but the configuration method is relatively cumbersome, usually used in conjunction with Spring, so you need to add the dependency of MyBatis and Spring integration:

    <!-- MyBatis整合Spring -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.2</version>
    </dependency>

Since the bottom layer of MyBatis is implemented by JDBC technology, after integrating Spring, Spring-JDBC support is also required, so add:

    <!-- Spring-JDBC -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>3.2.8.RELEASE</version>
    </dependency>

** Note: All dependencies that are prefixed with spring- in the same project should use the same version! **

#### 1.2.3. Setting goals

Use the prepared database and data table to insert 1 data into the `t_user` table.

Example:

1. Create database `siso_ums`

    ```
    CREATE DATABASE siso_ums;
    ```

2. Create a data table `t_user` in the database and add` username`, `password`,` phone`, `email`,` birthday` fields to it, and use the auto-incrementing `id` as the primary key

    ```
    CREATE TABLE t_user (
        id INT AUTO_INCREMENT,
        username VARCHAR(16) UNIQUE NOT NULL,
        password VARCHAR(16) NOT NULL,
        phone VARCHAR(20),
        email VARCHAR(32),
        birthday DATETIME,
        PRIMARY KEY(id)
    ) DEFAULT CHARSET=UTF8;
    ```

3. Add no less than 5 pieces of data, support Chinese

    ```
    INSERT INTO t_user (
        username, email, password, phone
    ) VALUES 
    ('root', '[email protected]', '123456', '13800138002'),
    ('java', '[email protected]', '123456', '13800138003'),
    ('spring', '[email protected]', '123456', '13800138004'),
    ('mysql', '[email protected]', '123456', '13800138005'),
    ('mybatis', '[email protected]', '123456', '13800138006');
    ```

4. Query all data

    ```
    SELECT 
        id, username, password, phone, email, birthday 
    FROM 
        t_user;
    ```

5. Query the data of the specified user name

    ```
    SELECT 
        id, username, password, phone, email, birthday 
    FROM 
        t_user
    WHERE 
        username='admin';
    ```

6. Number of statistics

    ```
    SELECT 
        COUNT(id) 
    FROM 
        t_user;
    ```

7. Delete the data with the specified id

    ```
    DELETE FROM t_user WHERE id=1;
    ```

8. Modify the password of the data with the specified id

    ```
    UPDATE t_user SET password='newpassword' WHERE id=1;

#### 1.2.4. Create interfaces and design abstract methods

Since user data needs to be operated, you should create an entity class that exactly matches the data table, that is, create the `cn.siso.mybatis.entity.User` class. The attributes in the class are consistent with the data table.

Create the `cn.siso.mybatis.mapper.UserMapper` interface and add abstract methods to the interface:

    Integer reg(User user);

Since the MyBatis framework returns the number of affected rows by default when executing INSERT, DELETE, and UPDATE statements, when designing abstract methods, as long as the corresponding SQL statement is added, deleted, or modified, the return value of the method is designed as Integer, And the meaning of the value must be the number of rows affected!

#### 1.2.5. Configure the SQL statement corresponding to the abstract method

Create a `mappers` folder under` src \ main \ resources` (because a complete project may require multiple files about MyBatis configuration SQL statements, in order to facilitate management, so create a special folder), create an xml file `UserMapper.xml` to the` mappers` folder just now.

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

 

Regarding the `UserMapper.xml` file, it is generally called a configuration mapping file. The root node is` <mapper> `, and the` namespace` attribute must be configured. The value is the name of the JAVA interface file matching the XML file:

    <!-namespace: Java interface corresponding to the current XML file->
    <mapper namespace = "cn.siso.mybatis.mapper.UserMapper">
    
   

Regarding data operations, in the `<mapper>` node, according to the type of operation, you can select `<insert>`, `<delete>`, `<update>`, `<select>`, this time, you should select `< insert> node, the value of the id attribute of the node is the name of the corresponding abstract method, and then manually add the parameterType attribute to configure the parameter type of the method, and the value is the full name of the User:

    <!-id: the name
    of the abstract method corresponding to the         node- > <!-parameterType: the data type of the parameter of the corresponding abstract method- >
    <insert id = "reg"
parameterType = "cn.siso.mybatis .entity.User ">
    </ insert>

Then, write the SQL statement to be executed inside the node, the value part uses `# {}` and the internal is the attribute name of the parameter `User` class:

    <insert id="reg"
        parameterType="cn.siso.mybatis.entity.User">
        INSERT INTO t_user (
            username, email, 
            password, phone, birthday
        ) VALUES (
            #{username}, #{email}, 
            #{password}, #{phone}, #{birthday}
        )
    </insert>

#### 1.2.6. Related configuration

First, you need to configure the database connection related parameters, that is: create a `db.properties` file under` src \ main \ resources`:

    url=jdbc:mysql://localhost:3306/siso_ums?useUnicode=true&characterEncoding=utf8
    driver=com.mysql.jdbc.Driver
    username=root
    password=root
    initialSize=5
    maxActive=50

Since you need to use the MySQL connection jar package and the database connection pool dbcp package, you should also add dependencies:

    <!-- MySQL -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>

    <!-- DBCP -->
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>

 

Spring-mvc, xml content:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
</beans>

 

Next, you need to read the above `db.properties` file through Spring, and apply the configured values ​​to the database connection data source (` BasicDataSource`). Since these configurations are related to the operation of the persistence layer, copy spring-mvc.xml` file (the content of the file has been provided above), and paste it as `spring-dao.xml`, delete the original configuration in the new` spring-dao.xml`, and add the new configuration:

    <!-Read db.properties->
    <util: properties id = "dbConfig"
        location = "classpath: db.properties" />
        
    <!-Configure the data source: BasicDataSource->
    <bean id = "dataSource " 
        class =" org.apache.commons.dbcp.BasicDataSource ">
        <!-In the following configuration->
        <!-The value of name is the attribute name (method name) in BasicDataSource->
        <!-value The value is to refer to the configuration file read             above- >
        <property name = "url" 
value = "# {dbConfig.url}" />
        <property name = "driverClassName" 
            value = "# {dbConfig.driver}" / >
        <property name = "username"  
            value="#{dbConfig.username}" />
        <property name="password" 
            value="#{dbConfig.password}" />
        <property name="initialSize" 
            value="#{dbConfig.initialSize}" />
        <property name="maxActive" 
            value="#{dbConfig.maxActive}" />
    </bean>

You can create a test class to verify that the above configuration is correct:

    public class TestDataSource {
    
        public static void main (String [] args) 
                throws SQLException {
            // Load the Spring configuration and get the Spring container
            AbstractApplicationContext ac
                = new ClassPathXmlApplicationContext (
                    "spring-dao.xml");
            
            // Get the object
            BasicDataSource from the Spring container ds 
                = ac.getBean ("dataSource", 
                        BasicDataSource.class);
            
            // test
            java.sql.Connection conn = ds.getConnection ();
            System.out.println (conn);
    
            // release resource
            ac.close ();
        }
    
    }

Since the configuration related to MyBatis has been handed over to Spring for management, in the follow-up, the entire environment needs to be known at runtime: the data source used, the location of the MyBatis interface file, and the location of the MyBatis mapping file, then continue in `spring -dao.xml` add configuration:

    <!-Configure MapperScannerConfigurer->
    <bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-Configure the package where the interface file is
        located- > <property name = "basePackage"
            value = "cn. siso.mybatis.mapper "/>
    </ bean>
    
    <!-configure SqlSessionFactoryBean->
    <bean class =" org.mybatis.spring.SqlSessionFactoryBean ">
        <!-configure which data source to use, the value of the ref attribute is The bean id of the pre-configured data source->
        <property name = "dataSource" 
            ref = "dataSource" />
        <!-Configure the location of the XML mapping file->
        <property name = "mapperLocations"
            value = "classpath : mappers / *. xml "/>
    </bean>

At this point, the configuration is all over!

#### 1.2.7. Perform unit testing

Create `TestUserMapper` class under` src \ test \ java` and write test method:

    @Test
    public void reg () {
        // Load the Spring configuration file and get the Spring container
        AbstractApplicationContext ac
            = new ClassPathXmlApplicationContext (
                "spring-dao.xml");
        
        // Get the required object: MyBatis interface object
        UserMapper userMapper 
            = ac .getBean ("userMapper", UserMapper.class);
        
        // Test execution
        User user = new User ();
        user.setUsername ("html");
        user.setPassword ("888888");
        Integer rows = userMapper.reg (user );
        System.out.println ("rows =" + rows);
        
        // release resources
        ac.close ();
    }

** The reason why the test class is placed in this location is because when the project is finally deployed, the content under test will not be deployed! Does not affect the actual development of the project! **

### 1.3. Query all data through MyBatis

#### 1.3.1. Setting goals

Query all the data in the current `t_user` table

#### 1.3.2. Designing abstract methods

Add a new abstract method in the `UserMapper.java` interface:

    List<User> getList();

#### 1.3.3. Configure Mapping SQL 

Add configuration in the `UserMapper.xml` file:

    <select id="getList"
        resultType="cn.siso.mybatis.entity.User">
        SELECT 
            id, username, password, phone, email, birthday
        FROM
            t_user
    </select>

** In MyBatis, the query executed must be configured with the `resultType` attribute on the` <select> `node! (You can also configure `resultMap`, choose one of two) **

** In MyBatis, all queries return the `List` collection by default, so when specifying` resultType`, the value is the data type stored in the `List` collection! **

### 1.4. Query by specifying conditions in MyBatis

#### 1.4.1. Setting goals

According to the user name, query a user's information

#### 1.4.2. Designing abstract methods

Add a new abstract method in the `UserMapper.java` interface:

    User getUserByUsername(String username);

** When querying, if the query result is defined as a specific data type instead of a List collection, MyBatis will further process the queried List collection (MyBatis query result must be a List collection), try to take out The first data in the List collection, if there is no data in the collection, it returns null. **

#### 1.4.3. Configure Mapping SQL 

Add configuration in the `UserMapper.xml` file:

    <select id="getUserByUsername"
        resultType="cn.siso.mybatis.entity.User">
        SELECT 
            id, username, password, phone, email, birthday
        FROM
            t_user
        WHERE
            username=#{username}
    </select>

** If the method corresponding to the SQL mapping of the query has only 1 parameter, there is no need to configure the `parameterType` attribute! **

### 1.5. Number of statistics

#### 1.5.1. Setting goals

Count the number of data in the current `t_user` table

#### 1.5.2. Designing abstract methods

Add a new abstract method in the `UserMapper.java` interface:

    Integer getCount();

#### 1.5.3. Configure Mapping SQL 

Add configuration in the `UserMapper.xml` file:

    <select id="getCount" resultType="java.lang.Integer">
        SELECT COUNT(id) FROM t_user
    </select>

** Even if the query result is `Integer`, a very common data type, you must configure` resultType`! **

### 1.6. Delete the data with the specified id

#### 1.6.1. Setting goals

Delete the corresponding data in the `t_user` table according to` id`

#### 1.6.2. Designing abstract methods

Add a new abstract method in the `UserMapper.java` interface:

    Integer deleteUserById(Integer id);

#### 1.6.3. Configure Mapping SQL 

Add configuration in the `UserMapper.xml` file:

    <delete id="deleteUserById">
        DELETE FROM t_user WHERE id=#{id}
    </delete>

### 1.7. Modify the password of the specified id data

#### 1.7.1. Setting goals

change Password

#### 1.7.2. Designing abstract methods

Add a new abstract method in the `UserMapper.java` interface:

    Integer changePassword(
            @Param("id") Integer id, 
            @Param("password") String password);

** When using MyBatis to process the data operation of the persistence layer (whether it is added, deleted, modified, or checked), as long as the method has more than 1 parameter (2 or more), each parameter must be before Use the `@Param ()` annotation, and define the name of the parameter in the annotation. Later, when configuring the SQL statement, the name filled in when using the ## {} `syntax is the name used in the annotation at this time! **

#### 1.7.3. Configuration mapping SQL 

Add configuration in the `UserMapper.xml` file:

    <update id="changePassword">
        UPDATE 
            t_user 
        SET 
            password=#{password}
        WHERE 
            id=#{id}
    </update>

 

### 1.8. Summary of basic usage of MyBatis

-The role of MyBatis: simplify the development of the persistence layer without writing JDBC related code;

-Each function requires an abstract method and matching SQL mapping;

-If the abstract method has more than one parameter, it must be annotated with `@ Param`;

-If you add, delete, or change, the return value of the abstract method can be `Integer`, which indicates the number of rows affected. Of course, if you do n’t care about this return value, you can also design the return value as` void`;

-If you perform a query operation, the return value of the abstract method can be `List` or the type of matching entity class, or even other types such as` Integer`, which can be designed according to your needs; in fact, each query returns a `List `, Only, if the designed return value is the type of the entity class, MyBatis will try to retrieve the first data from the` List`, if the retrieval fails, it returns `null`;

-When configuring SQL mapping, the node should be selected according to the type of SQL statement executed;

-The id attribute must be configured on each node, indicating the name of the matching abstract method;

-All `<select>` nodes must be configured with `resultType`;


 

Posted 33 original articles · praised 4 · visits 2714

Guess you like

Origin blog.csdn.net/qq_41650000/article/details/83515799