mybatis learning notes 1

mybatis
Advantages of mybatis
1. Compared with JDBC, the amount of code is reduced by 50%
2.mybatis is the simplest persistence framework, small and easy to learn
3.mybatis is quite flexible and will not impose any impact on the existing design of application programs or databases. SQL is written in XML and completely separated from the program code to reduce the degree of coupling, facilitate unified management and optimization, and can be reused.
4. Provide XML tags to support writing dynamic SQL statements
5. Provide a mapping label to support the mapping between the object and the ORM field of the database

shortcoming
1. The workload of writing SQL statements is large, especially with many fields and associated tables. It has certain requirements for developers to write SQL statements.
2. The SQL statement depends on the database, resulting in poor mobility of the database, and the database cannot be changed randomly.

mybatis use
1. New maven project, POM xml

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.11</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.6</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
        <scope>test</scope>
    </dependency>

<resource>
    <!-- Because I want to Mapper.xml Documents and Mapper Interfaces are put together, so src/main/java Add to resource search directory  -->
    <directory>src/main/java</directory>
    <includes>
        <include>**/*.properties</include>
        <include>**/*.xml</include>
    </includes>
    <filtering>false</filtering>
</resource>

</dependencies>
</project>

2. Create a new table in the database

CREATE TABLE t_account(
id INT PRIMARY KEY auto_increment,
username VARCHAR(11),
password VARCHAR(11),
age INT
)

3. Create an entity class corresponding to the data table

package com.southwind.entity;

import lombok.Data;

@Data
public class Account {
    private long id;
    private String username;
    private String password;
    private int age;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }

    public long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

4. Create mybatis configuration file config xml

<?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">
<!-- mybatis Master profile for -->
<configuration>
    <!-- to configure mybatis Operating environment -->
    <environments default="development">
        <!-- to configure mysql environment -->
        <environment id="development">
            <!-- Configure transaction type -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- Configure data source (connection pool) -->
            <dataSource type="POOLED">
                <!-- Four basic information for configuring and connecting to the database -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis?serverTimezone=GMT%2B8&amp;useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
 <!-- Specify the location of the mapping profile, which refers to each dao Stand alone profile -->
    <mappers>
        <mapper resource="com/ithema/Mapper/UserMapper.xml"/>
    </mappers>
</configuration>

5. Use the native interface (that is, use the implementation class of the interface)

(1)mybatis The framework needs to be customized by developers SQL Statement, written in Mapper.xml In the file, in the actual development, the corresponding file will be created for each entity class Mapper.xml,Define the method to manage the data of this object SQL. 
<?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">
<mapper namespace="com.southwind.Mapper.AccountMapper">
    <!--Configure query all-->
    <insert id="save" parameterType="com.southwind.entity.Account">
        insert into t_account(username,password,age) values (#{username},#{password},#{age})
    </insert>
</mapper>

namespace is usually set to the form of package + file name where the file is located
The insert tag indicates that the add operation is performed
The select tag indicates that the query operation is performed
The update tag indicates that the update operation is performed
delete indicates that the deletion operation is performed
id is the parameter used when actually calling the mybatis method
parameterType is the data type of the parameter when the corresponding method is called.

(2) In the global configuration file config Register UserMapper.xml xml

   <mappers>
        <mapper resource="com/southwind/Mapper/AccountMapper.xml"/>
    </mappers>
</configuration>

(3) Call the mybatis native interface to perform the selection operation

public static void main(String[] args) throws  Exception {
    //1. Read the configuration file
    InputStream in= Test.class.getClassLoader().getResourceAsStream("Config.xml");
    //2. Create SqlSessionFactory factory
    SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
    SqlSessionFactory factory=builder.build(in);
    //3. Use factory to produce SqlSession object
    SqlSession session=factory.openSession();

    String statement="com.southwind.Mapper.AccountMapper.save";
    Account account=new Account(1L,"Zhang San","123",22);
    session.insert(statement,account);
    session.commit();
}

Implement custom interface through Mapper proxy
Customize the interface and define relevant business methods
Write mapper corresponding to the method xml.

1. User defined interface

package com.southwind.reposity;

import com.southwind.entity.Account;

import java.util.List;
public interface AccountReposity {
        public int save(Account account);
        public int update(Account account);
        public  int deleteById(long id);
        public List<Account> findAll();
        public  Account findById(long id);
}

2. Create mapper corresponding to the interface XML to define the SQL statement corresponding to the interface method.
The statement tab can select Insert, delete, update and select according to the business executed by SQL
The mybatis framework will automatically create the proxy object of the interface implementation class according to the rules
Rules:

Mapper.xml in namespace Is the corresponding full class name in the interface
Mapper.xml in statement of id Is the corresponding method name in the interface
Mapper.xml in statement of parameterType It is consistent with the parameter type of the corresponding method in the interface.
Mapper.xml in statement of resultType It is consistent with the return value type of the corresponding method in the interface.
<?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">
<mapper namespace="com.southwind.reposity.AccountReposity">
   <insert id="save" parameterType="com.southwind.entity.Account">
       insert into t_account(username,password,age) values (#{username},#{password},#{age})
   </insert>
         <update id="update" parameterType="com.southwind.entity.Account">
             update  t_account set username=#{username},password=#{password},age=#{age} where id=#{id}
         </update> 
    <delete id="deleteById" parameterType="long">
        delete from t_account where id=#{id}
    </delete>
    <select id="findAll" 
If the return value is a collection, the type of generic type in the collection is returned, i.e Account
resultType="com.southwind.entity.Account">
        select  * from t_account
    </select>
    <select id="findById" parameterType="long" resultType="com.southwind.entity.Account">
        select  * from t_account where id=#{id}
    </select>
    </mapper>

3. In config Register accountrepository. XML xml

<mappers>
       <mapper resource="com/southwind/reposity/AccountReposity.xml"></mapper>
</mappers>

4. Call the proxy object of the interface to complete relevant business

package com.southwind.test;

import com.southwind.entity.Account;
import com.southwind.reposity.AccountReposity;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

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

public class Test2 {
    public static void main(String[] args) {
        InputStream inputStream=Test.class.getClassLoader().getResourceAsStream("Config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        //Gets the proxy object that implements the interface
        AccountReposity accountReposity=sqlSession.getMapper(AccountReposity.class);
        //Add object
        Account account=new Account(2L,"Li Si","23456",25);
        accountReposity.save(account);
        sqlSession.commit();
        //Query object
        Account account1=accountReposity.findById(3L);
        System.out.println(account1);
        sqlSession.close();
        //modify
        Account account2=accountReposity.findById(3L);
        account2.setUsername("Xiao Ming");
        account2.setPassword("5896");
        account2.setAge(18);
        int result=accountReposity.update(account2);
        sqlSession.commit();
        System.out.println(result);
        sqlSession.close();
        //delete
        int result1=accountReposity.deleteById(3L);
        System.out.println(result);
        sqlSession.commit();
        sqlSession.close();
        /*List<Account> list=accountReposity.findAll();
        for (Account account : list) {
            System.out.println(account);
        }
        sqlSession.close();*/

    }
}

Mapper.xml

statement label: select,update,delete,insert Corresponding to query, modify, delete and add operations respectively.
parameterType: Parameter data type

1. Basic data type: query Account by id

<select id="findById" parameterType="long" resultType="com.southwind.entity.Account">
    select  * from t_account where id=#{id}
</select>

2.string type

<select id="findByName" parameterType="java.lang.String" resultType="com.southwind.entity.Accoun">
    select * from t_account username=#{username};
</select>

3. For packaging, check the Account by id

<select id="findById" parameterType="java.lang.Long" resultType="com.southwind.entity.Account">
    select  * from t_account where id=#{id}
</select>

4. Multiple parameters, query Accuont by name and age

<select id="findByNameAndAge">
    select * from t_account where username=#{param1} and age=#{param2}
</select>

5.JavaBean

<update id="update" parameterType="com.southwind.entity.Account">
  update  t_account set username=#{username},password=#{password},age=#{age} where id=#{id}
     </update>

resultType: result type
1. Basic data type, count the total number of accounts

<select id="count" resultType="int">
    select count(id) from t_account
</select>

2. For packaging, count the total number of accounts

<select id="count2" resultType="java.lang.Integer">
    select count(id) from t_account
</select>

3.string type, query the name of account through id

<select id="findNameById" resultType="java.lang.String">
    select username from t_account where id=#{id}
</select>

4.JavaBean

<select id="findById" parameterType="long" resultType="com.southwind.entity.Accoun">
  select * from t_account where id=#{id}  
</select>

Hierarchical Queries
1. One to many
Entity class student

package com.southwind.entity;

import lombok.Data;

@Data
public class Student {
    private long id;
    private String name;
    private Classes classes;
}

Entity classes

package com.southwind.entity;

import lombok.Data;

import java.util.List;

@Data
public class Classes {
    private long id;
    private String name;
    private List<Student> students;
}

Interface studentrepository

package com.southwind.reposity;

import com.southwind.entity.Student;

public interface StudentReposity {

    public  Student findById(long id);
}

Mapping profile

<?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">
<mapper namespace="com.southwind.reposity.StudentReposity">
     <!--Indirect mapping-->
    <resultMap id="studentMap" type="com.southwind.entity.Student">
        <!--take id Map to Student In entity class id-->
        <id column="id" property="id"></id>
        <!--take name Map to Student In entity class id-->
        <result column="name" property="name"></result>
        <association property="classes" javaType="com.southwind.entity.Classes">
            <!--take cid Map to Classes In entity class id-->
            <id column="cid" property="id"></id>
            <!--take cname Map to Classes In entity class id-->
            <result column="cname" property="name"></result>
        </association>

    </resultMap>
    <select id="findById" parameterType="long" resultMap="studentMap">
        SELECT s.id ,s.name,c.id as cid,c.name as cname from student s,classes c where s.id=#{id} and s.cid=c.id
    </select>
</mapper>

Test class

package com.southwind.test;


import com.southwind.reposity.StudentReposity;
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;

public class Test3  {
public static void main(String[]args) throws IOException {

    InputStream inputStream=Test.class.getClassLoader().getResourceAsStream("mybatis/config.xml");
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
    SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(inputStream);
    SqlSession sqlSession=sqlSessionFactory.openSession();
    //Gets the proxy object that implements the interface
    StudentReposity studentReposity=sqlSession.getMapper(StudentReposity.class);
    System.out.println(studentReposity.findById(1L));
    sqlSession.close();

        }
}

2, Many to many

reverse engineering
mybatis framework needs: entity class, custom Mapper interface and Mapper xml
In traditional development, the above three components need to be created manually by developers. Reverse engineering can help developers create three components, reduce the workload of developers and improve work efficiency.

How to use:
MybatisGenerator, MBG for short, is a code generator specially customized for mybatis framework developers, which can automatically generate mybatis framework entity classes, mapper interfaces and mapper XML, supporting basic CRUD operations.

New Maven project. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>reverse engineering </artifactId>
    <version>1.0-SNAPSHOT</version>
<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.11</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.3.2</version>
    </dependency>
</dependencies>
</project>

Create MBG configuration file generatorconfig xml
1. JDBC connection: configure database connection information
2.javaModelGenerator configures the generation strategy of JavaBeans
3.sqlMapGenerator configures SQL mapping file generation strategy
4.JavaClienGenerator configures the generation strategy of Mapper interface
5.table configuration target data table

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <context id="testTable4" targetRuntime="mybatis3">
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncodeing=UTF-8"
                        userId="root"
                        password="root"
        ></jdbcConnection>
        <javaModelGenerator targetPackage="com.southwind.entity" targetProject="./src/main/java"></javaModelGenerator>
        <sqlMapGenerator targetPackage="com.southwind.repository" targetProject="./src/main/java"></sqlMapGenerator>
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.southwind.repository" targetProject="./src/main/java"></javaClientGenerator>
        <table tableName="t_user" domainObjectName="User"></table>
    </context>
</generatorConfiguration>

Delayed loading
What is deferred loading?

Improving the running efficiency of the program is aimed at the operation of the persistence layer. Under specific circumstances, you can access a specific database. In other cases, you can not access some tables, which reduces the interaction times of java application in the database to a certain extent

mybatis cache

Using cache can reduce the interaction times of java application in the database, so as to improve the running efficiency of the program. For example, if an object with id=1 is queried, the object will be automatically saved to the cache after the first query. The next query is to take the object directly from the cache without accessing the object again.

mybatis cache classification

1. L1 cache: SqlSession level. It is enabled by default and cannot be closed.
To operate the database, you need to create a SqlSession object in which a HashMap is used to cache data. The cache data areas between different sqlsessions do not affect each other.

The scope of the first level cache is SqlSession. When the same SQL statement is executed twice in the same SqlSession, the results will be saved to the cache after the first execution, and the second query is obtained directly from the cache.

It should be noted that if the SqlSession performs DML operations (insert,update,delete), Mybatis must empty the cache to ensure the accuracy of the data.

2. L2 cache: Mapper level. It is off by default and can be turned on
When using L2 cache, multiple sqlsessions use the same Mapper's SQL statement to operate the database, and the resulting data will be stored in L2 cache. HashMap is also used for data storage. Compared with L1 cache, L2 cache has a wider range. Multiple sqlsessions can share L2 cache, and L2 cache spans the of SqlSession.
The L2 cache is shared by multiple sqlsessions. Other scopes are the same namespace of Mapper. Different sqlsessions execute SQL statements under the same namespace twice, and the parameters are also equal. After the first execution is successful, the data will be saved to the L2 cache, and the second class will directly take the data from the L2 cache

mybatis dynamic SQL
Reduce the workload of developers, and the program can be automatically determined according to business parameters

Create basic mybatis project process

mybatis environment construction:
1. Create maven project and import coordinate system
2. Create entity classes and dao interfaces
3. Create the main configuration file sqlmapconfig. Of mybatis xml
4. Create mapping configuration file iuserdao xml

Precautions for environmental construction:
1. Create sqlmapconfig XML and IUserDao Java is to keep up with our previous knowledge. In creating mybatis, it also calls the operation interface name and mapping file of the persistence layer Mapper, so IUserDao and IUserMapper are the same
2. The packages created in idea are different.
When the package is created: com ithema. Dao is a three-level structure
When creating the directory: com ithema. Dao is a primary directory
3. The mapping file location of mybatis must be the same as the package structure of dao interface
4. The value of the mapper tag namespace attribute of the mapping configuration file must be the fully qualified class name of the dao interface
5. For the operation configuration (select) of the mapping configuration file, the value of id attribute must be the method name of dao interface

When points 3, 4 and 5 are followed, there is no need to write in development dao Implementation class
//1. Read the configuration file
InputStream in= Resources.getResourceAsStream("SqlmapConfig.xml");
//2. Create SqlSessionFactory factory
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
SqlSessionFactory factory=builder.build(in);
//3. Use factory to produce SqlSession object
SqlSession session=factory.openSession();
//4. Create Dao interface proxy object with SqlSession
IUserDao userDao=session.getMapper(IUserDao.class);
//5. Use the proxy object to execute the method
List<User> users=userDao.findAll();
//6. Release resources
session.close();
in.close();
Note: don't forget to inform in the mapping configuration mybatis Which entity do you want to encapsulate
 Configuration method: specify the fully qualified class name of the entity class

Keywords: Java Mybatis

Added by knight47 on Thu, 27 Jan 2022 23:39:14 +0200