Mybatis Environment Configuration and CRUD

Keywords: Mybatis xml Java Database

What is MyBatis?

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping.MyBatis eliminates almost all JDBC code and setting parameters and getting result sets.MyBatis can configure and map raw types, interfaces, and Java POJO s (Plain Old Java Objects, plain old Java objects) as records in the database through simple XML or annotations.

MybatisUtils

This is a custom tool class that gets the sqlSession instantiation object as follows:

SqlSession sqlSession = MybatisUtils.getSqlSession();

Code:

package com.skdjq.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;

//sqlSessionFactory --> sqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            //Getting sqlSessionFactory object using Mybatis
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //Now that we have the SqlSessionFactory, as the name implies, we can get an instance of SqlSession from it.
    // SqlSession provides all the methods required to execute SQL commands in a database.
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

Configuring the Mybatis environment

Here we will focus on building projects with Maven.

First, place the following dependent codePom.xmlFile:

<dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

Then create a new mybatis-under the resources directoryConfig.xmlFile, configure as follows:

<?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>
    <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/Database name? useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--resource The path depends, typically sql Statement's xml File Path-->
        <mapper resource="com/skdjq/Dao/UserMapper.xml"/>
    </mappers>
</configuration>

Be careful:

There are two ways to configure:

  • resource: corresponds to / and.xml
<mappers>
    <mapper resource="com/skdjq/Dao/UserMapper.xml"/>
</mappers>
  • class: corresponding to the interface
<mappers>
    <mapper class="com.skdjq.Dao.UserMapper"/>
</mappers>

Notes about class es:

  • Interface and its Mapper profile must have the same name!
  • The interface and its Mapper profile must be in the same package!

Write an interface:

package com.skdjq.Dao;
import com.skdjq.pojo.User;
import java.util.List;

public interface UserDao {
    List<User> getUserList();
    User getUserID(int id);
    int addUser(User user);
}

xml file to write sql statement:

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
	<!--namespace Is Interface Path-->
<mapper namespace="com.skdjq.Dao.UserDao">
	<!--This section can be customized-->
    <select id="getUserList" resultType="com.skdjq.pojo.User">
        select * from mybatis.user;
    </select>
</mapper>

Note: It is best not to have Chinese comments in the xml file!

CRUD for Mybatis

UserMapper.xml The configuration is as follows:

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.skdjq.Dao.UserDao">

    <select id="getUserList" resultType="com.skdjq.pojo.User">
        select * from mybatis.user;
    </select>

    <select id="getUserID" parameterType="int" resultType="com.skdjq.pojo.User">
        select * from mybatis.user where id=#{id};
    </select>

    <insert id="addUser" parameterType="com.skdjq.pojo.User">
        insert into mybatis.user (id,name,pwd) values(#{id},#{name},#{pwd});
    </insert>

    <update id="updateUser" parameterType="com.skdjq.pojo.User">
        update mybatis.user set name=#{name} ,pwd=#{pwd} where id=#{id};
    </update>

    <delete id="deleteUser" parameterType="com.skdjq.pojo.User">
        delete from mybatis.user where id=#{id};
    </delete>

</mapper>

Tables for functions such as select update, such as: select * fromMybatis.user;

If there is no database in the IDEA, write the table name directly.If a database is connected in IDEA, you need to write the database name. table name.

Interface UserDao:

package com.skdjq.Dao;

import com.skdjq.pojo.User;

import java.util.List;

public interface UserDao {
    List<User> getUserList();
    User getUserID(int id);
    int addUser(User user);
    int updateUser(User user);
    int deleteUser(int id);
}

User does not write, the code is too long, there are three parameters id, name, pwd.

UserDaoTest:

package com.skdjq.Dao;
import ...
    
public class UserDaoTest {

    @Test

    //check
    public void test(){
        //Get SqlSession object
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //getMapper
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();
        for(User user:userList){
            System.out.println(user.getName() + "    " + user.getId() + "    " + user.getPwd());
        }
        //Close SqlSession
        sqlSession.close();
    }
    @Test
    //Check by id
    public void testID(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User userID = mapper.getUserID(1);
        System.out.println(userID.getName() + "==" + userID.getId() + "==" + userID.getPwd());
        sqlSession.close();
    }
    @Test
    //increase
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.addUser(new User(4, "zhaoLiu", "444444"));
        System.out.println("Add Success!!");
        //Submit Transaction----------------------------------------------- Additions and deletions need to submit a transaction!!
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    //Delete
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.deleteUser(4);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    //change
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.updateUser(new User(4,"Ha-ha","000000"));
        sqlSession.commit();
        sqlSession.close();
    }

}

Be careful:

  • All additions and deletions must be transaction committed!(sqlSession.commit())
  • SqlSession must be closed after all operations are completed!(sqlSession.close())

parameterType

The parameterType is the input parameter, and when configuring it, configure the corresponding input parameter type.

1. MyBatis's incoming parameter parameterType has two types

Basic data types: int, string, long, Date;

Complex data types: classes (JavaBean, Integer, and so on) and Map

2. How to get the value in the parameter:

Basic data type: #{parameter} Get the value in the parameter

Complex data type: #{attribute name}, map is #{key}

Posted by smitho on Mon, 15 Jun 2020 18:22:30 -0700