Integrating mybatis into the learning record 402@ project

The company's project is an old project without any framework. The bottom layer is a self encapsulated framework, and there is no separation of controller, service and dao layers. Therefore, it is extremely uncomfortable, especially the sql part. Because it does not use mybatis, it is very complicated, and the original sql is still used. Therefore, I still want to integrate mybatis into the project to make the operation of sql more convenient and improve readability.

Add dependency

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

    <!--MySql Drive dependency-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.25</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <!-- Connection pool dependency: Alibaba's druid(Other options can be selected. At present, this one is better) -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.16</version>
    </dependency>

mybatis-config.xml configuration file

Create this file and put it in the resource directory. The initial template is as follows
This file is mainly used to configure database confidence and mapper XML file location, etc

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

<configuration>
    <!--Configure the order of labels:(properties?, settings?, typeAliases?,
        typeHandlers?, objectFactory?, objectWrapperFactory?,
        reflectorFactory?, plugins?, environments?,
        databaseIdProvider?, mappers?)-->


</configuration>

jdbc.properties configuration file

Used to configure database information
Note that the connector in properties is &, and the connector in xml file is &&

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306 / database name? useSSL=false&serverTimezone=UTC
jdbc.username=user name
jdbc.password=password

mybatis-config.xml configuration

Primary configuration database connection
There will be usermapper XML, configure it here first

<?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>
    <properties resource="jdbc.properties"></properties>
    <settings>
        <setting name="logImpl" value="LOG4J"/>
        <!--        true Turn on delayed loading-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--        true Turn on demand loading-->
        <setting name="aggressiveLazyLoading" value="true"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    
    <!--mapper.xml Path configuration for-->
    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>
    
</configuration>

Tools - that's the core

The core of MyBatis is sqlsessionfactorybuilder, SqlSessionFactory and SqlSession objects, which are created in turn. Finally, we want to get the SqlSession object, which is used to access the data. However, each time we access, we need to write a series of processes to create the SqlSession object, and then close it in reverse, Makes the code a lot of repetition.
Therefore, we can write a tool class to help us complete these operations. Each time we access data, we call the tool class to obtain the SqlSession object, and then use the tool class to close the object.

package com.qianfeng.utils;

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;

public class MyBatisUtils {

    // Get SqlSessionFactory
    private static SqlSessionFactory factory;

    //Create ThreadLocal to bind the SqlSession object in the current thread
    private static final ThreadLocal<SqlSession> t1 = new ThreadLocal<SqlSession>();

    //Load the configuration information and build the session factory
    static{
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Get connection (get SqlSession of current thread from t1)
    private static SqlSession openSession(){
        SqlSession session = t1.get();
        if (session == null){
            session = factory.openSession();
            t1.set(session);
        }
        return session;
    }

    // Get connection (newly created)
    public static SqlSession getSession(){
        return factory.openSession();
    }

    // Release connection (release SqlSession in current thread)
    public static void closeSession(){
        SqlSession sqlSession = t1.get();
        sqlSession.close();
    }

    // Commit transaction (commit the transaction managed by SqlSession in the current thread)
    public static void commit(){
        SqlSession sqlSession = openSession();
        sqlSession.commit();
        closeSession();
    }

    // Rollback transaction (rollback the transaction managed by SqlSession in the current thread)
    public static void rollback(){
        SqlSession sqlSession = openSession();
        sqlSession.rollback();
        closeSession();
    }

    // Get interface implementation class object
    public static <T> T getMapper(Class<T> mapper){
        SqlSession sqlSession = openSession();
        return sqlSession.getMapper(mapper);
    }
}

Note that if it is a non query operation, you must submit or rollback the operation.

This completes the basic configuration. The next step is to add entity classes, dao layer and service layer

Entity class

package com.qianfeng.pojo;

import java.util.Date;

public class User {

    private Integer id;
    private String username;
    private String password;
    private Date birthday;

    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 String getPassword() {
        return password;
    }

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

    public Date getBirthday() {
        return birthday;
    }

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

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

dao

Note that only the interface is needed here

package com.qianfeng.dao;

import com.qianfeng.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;
public interface IUserDao {

	List<User> findByIdAndName(@Param("id") Integer id, @Param("name") String username);
}

servcice

package com.qianfeng.service;

import com.qianfeng.pojo.User;

import java.util.List;

public interface UserService {
    List<User> findByIdAndName(Integer id, String username);
}

package com.qianfeng.service.imp;

import com.qianfeng.dao.IUserDao;
import com.qianfeng.pojo.User;
import com.qianfeng.service.UserService;
import com.qianfeng.utils.MyBatisUtils;

import java.util.List;

public class UserServiceImp implements UserService {

    IUserDao userDao = MyBatisUtils.getMapper(IUserDao.class);

    @Override
    public List<User> findByIdAndName(Integer id, String username) {
        return userDao.findByIdAndName(id, username);
    }
}

mapper.xml

I put this file in resource/mapper here
mybatis-config. The path of this file is configured in the XML configuration

<?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-->
<mapper namespace="com.qianfeng.dao.IUserDao">

    <select id="findByIdAndName" resultType="com.qianfeng.pojo.User">
        select * from t_user where id=#{id}
        <if test="name!=null">
            or username like concat("%",#{name},"%")
        </if>
    </select>

</mapper>

test

package com.qianfeng.service.imp;

import com.qianfeng.pojo.User;
import junit.framework.TestCase;
import org.junit.Test;

import java.util.List;

public class UserServiceImpTest extends TestCase {
    @Test
    public void test() {
        UserServiceImp userServiceImp = new UserServiceImp();
        List<User> users = userServiceImp.findByIdAndName(1, "zhangsan");
        System.out.println(users);
    }
}

PS

If you want to automatically generate entity classes, dao, mapper XML, you can use the reverse generation tool of idea;


If you want mapper XML and dao have corresponding arrows. You can use the Free Mybatis plugin.
Click to switch

Added by Ghettobusta on Tue, 08 Mar 2022 23:27:48 +0200