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-->

    <!--MySql Drive dependency-->

    <!-- -->
    <!-- Connection pool dependency: Alibaba's druid(Other options can be selected. At present, this one is better) -->

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 "-// Mapper 3.0//EN"

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

</configuration> configuration file

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

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

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 "-// Config 3.0//EN"
    <properties resource=""></properties>
        <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"/>
    <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}"/>
    <!--mapper.xml Path configuration for-->
        <mapper resource="mapper/UserMapper.xml"/>

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.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


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
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {

    // Get connection (get SqlSession of current thread from t1)
    private static SqlSession openSession(){
        SqlSession session = t1.get();
        if (session == null){
            session = factory.openSession();
        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();

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

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

    // 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) { = 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;

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


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);


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);

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


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 "-// Mapper 3.0//EN"
<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},"%")



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 {
    public void test() {
        UserServiceImp userServiceImp = new UserServiceImp();
        List<User> users = userServiceImp.findByIdAndName(1, "zhangsan");


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