Mybatis start

Time:2022-5-19

Mybatis:

A persistence layer framework that simplifies SQL operations. Development only needs to focus on specific SQL statements

Traditional JDBC: 1 Operation SQL 2 Operate connection, station (an object that sends SQL to the database), resultset, etc

ORM framework: object relationship matching, which transforms the data in relational database into objects in object-oriented program

Hibernate (automatic SQL) and mybatis (custom SQL)

1. Introducing dependency in POM

Mybais only needs this dependency to complete
<dependency>
     <groupId>org.mybatis</groupId>
     <artifactId>mybatis</artifactId>
     <version>3.4.6</version>
</dependency>
    
However, it is necessary to operate the database, so the connection database driver is introduced
<dependency>
         <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.26</version>
</dependency>
 
Add a dependency of the test class for testing
<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
</dependency>

2.mybatis.xml

Write the mybatis core configuration file (put it in the resource directory)

<?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 core file-->
<configuration>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/hualian?useSSL=false&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- Set mapper XML is important to register in the core configuration file of mybatis!! -- > >
    <mappers>
        <mapper resource="com/gxa/hualian/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

3. Introduce mapper in POM xml

In order to load the XML file of mapper under the Java folder
<build>
   <resources>
      <resource>
         <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
</build>

4. Write java code

pojo/mapper/test

User

public class User implements Serializable {

    private Long id;
    private String name;
    private Integer points;
    private String phone;
    private Timestamp regTime;

    public User(Long id, String name, Integer points, String phone, Timestamp regTime) {
        this.id = id;
        this.name = name;
        this.points = points;
        this.phone = phone;
        this.regTime = regTime;
    }

    public User() {
    }
}

UserMapper

public interface UserMapper {

    void   add(User user);

    void deleteById(Long id);

    void  update(User user);

    List<Map> selectAll();
}

UserMapper.xml

<?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.gxa.hualian.mapper.UserMapper">
    <!-- Add, delete, modify and query SQL -- >
    <insert id="add" parameterType="com.gxa.hualian.pojo.User">
        insert into `user` (`name`,`phone`,`regTime`) values (#{name},#{phone},#{regTime})
    </insert>

    <delete id="deleteById" parameterType="long">
        delete from `user` where id=#{id}
    </delete>

    <update id="update" parameterType="com.gxa.hualian.pojo.User">
        update `user` set `name`=#{name},`phone`=#{phone},`regTime`=#{regTime}
    </update>

    <select id="selectAll" resultType="java.util.Map">
        select * from `user`
    </select>

Test

public class TestUser {

    UserMapper mapper=null;
    SqlSession sqlSession = null;
    @Before
    //To get sqlsession
    public void init() throws IOException {
        //Resources: a file stream reading tool provided by mybatis
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
        //Instantiate a builder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //Get a factory object through builder
        SqlSessionFactory factory = builder.build(resourceAsStream);
        //Get the session object through opensession. The default is to submit the transaction manually
        //Sqlsession provides all the methods required to execute SQL commands in the database
        sqlSession= factory.openSession();

        //Get the proxy object of mapper interface
        mapper= sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void add(){

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        User = new user ("test", 0, "7898", timestamp);

        //Method for obtaining proxy object readjustment
        mapper.add(user);

        //Sqlsession's own methods also have additions, deletions, modifications and queries. The statement parameter (the first parameter) should be consistent with the method name in the interface
        sqlSession.insert("add", user);

        sqlSession.commit();
    }

    @Test
    public void deleteById(){
        mapper.deleteById(37L);
        sqlSession.commit();
    }

    @Test
    public void update(){
        Timestamp timestamp1 = new Timestamp(System.currentTimeMillis());
        User user1 = new user (44l, "test 4", 0, "+ 65 + 6565 +", timestamp1);
        sqlSession.update("update", user1);
        sqlSession.commit();
    }


    @Test
    public void selectAll(){

        List<Map> maps = mapper.selectAll();
        System.out.println(maps.size());
        for (Map map : maps) {
            System.out.println(map);
        }
    }

}

Pit encountered:

1. When there is no spring management, you need to create your own sqlsession if you want the mapper object

2. The XML file is not imported into POM, and the report cannot find usermapper XML error

Label configuration resolution:

Mappers: mapper, usermapper The configuration in the XML file is mapped to a specific mapper XML file

<!-- Set mapper XML is registered in the core configuration file of mybatis -- >
    <mappers>
        <mapper resource="com/gxa/hualian/mapper/UserMapper.xml"/>
    </mappers>

Namespace: used to bind Dao interface

<mapper namespace="com.xxx.hualian.mapper.UserMapper">
    ...
</mappe>

Environments: the environment configuration collection can configure multiple databases

Environment: specific implementation of environment configuration

Connection pool: the server creates multiple connections to the database at one time and saves multiple connections in one connection pool object. The next time there is a request to operate the database, it directly obtains a connection from the connection pool and continues to put it back into the connection pool instead of closing it after use, which can save the resources of creating / releasing connections

//Default: development mode work mode
<environments default="development">
 //ID: Specifies the unique ID of the current environment
        <environment id="development">
//Transactionmanager: transaction manager type: JDBC - using JDBC's native transaction management method, both commit and rollback need to be manually executed
            <transactionManager type="JDBC"/>
//Using datasource: pooled datasource
            <dataSource type="POOLED">
//Property: property, connection driver, URL, user name and password
                <property name="driver" value="com.mysql.jdbc.Driver"/>
//Usessl: SSL protocol is used to ensure data security and correctness. The default is true
                <property name="url" value="jdbc:mysql://localhost:3306/hualian?useSSL=false&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>