[SpringBoot] data persistence: mybatis uses

If you eat when you are hungry, sleep when you are sleepy, drink when you are thirsty, life will be boring
Source address: https://github.com/keer123456789/springbootstudy/tree/master/mybatisdemo

1. Project configuration

1.1 maven dependency configuration

It mainly depends on mysql and mybatis. Pay attention to the version of mysql and make changes according to your version.

	<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>

        </dependency>
    </dependencies>

1.2 mysql configuration

Add mysql configuration in application.properties and modify the configuration content as required. The database file used this time, mybatis.sql, is in the project.

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

1.3 mybatis configuration

Create the mybatis folder under the resource folder and add the mybatis-config.xml configuration file, which is the basic configuration file of mybatis

<?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>
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer" />
        <typeAlias alias="Long" type="java.lang.Long" />
        <typeAlias alias="HashMap" type="java.util.HashMap" />
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
        <typeAlias alias="ArrayList" type="java.util.ArrayList" />
        <typeAlias alias="LinkedList" type="java.util.LinkedList" />
    </typeAliases>
</configuration>

Add the profile location in application.properties

mybatis.config-location=classpath:mybatis/mybatis-config.xml

2. Two ways of use

mybatis provides two methods in spring boot, one is XML, the other is annotation.
Only the usage of mybatis is explained below. For the complete code, see: github>>>

2.1 using XML

2.1.1. create the user table in the database

As shown in Figure 1:

2.1.2. Create User object class

As shown in Figure 2: create the corresponding member variables and add getter(),setter() and toString() methods

2.1.3. Add Mapper map

This time, it is explained by adding, deleting, modifying and checking four methods

public interface UserMapper {
    /**
     * Get all user information
     * @return
     */
    List<User> getAll();

    /**
     * Query user information by id
     * @param id
     * @return
     */
    User getUserInfoByID(String id);

    /**
     * Add user information
     * @param user
     * @return
     */
    int addUserInfo(User user);

    /**
     * Change user name
     * @param name
     * @param id
     * @return
     */
    int updateUserNameByID(String name,String id);

    /**
     * Delete user information according to user ID
     * @param id
     * @return
     */
    int deleteUserInfoByID(String id);

}

2.1.4 add the corresponding xml file

Create the corresponding XML file: UserMapper.xml, and implement all the sql statements of each method here:

  • The namespace in the mapper must correspond to the corresponding mapper file
  • resultMap is to map the queried data to the corresponding object class
  • The rest of the middle id attribute should correspond to the method name
  • In sql statement, the {* *} should be consistent with the input parameter name of the corresponding method. If the input parameter is an object class, it should be corresponding to the corresponding member variable
<?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.keer.mybatisdemo.mapper.UserMapper">

    <resultMap id="BaseResultMap" type="com.keer.mybatisdemo.pojo.User">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="sex" property="sex" jdbcType="VARCHAR"/>

    </resultMap>

    <select id="getAll" resultMap="BaseResultMap">
        select * from user;
    </select>

    <select id="getUserInfoByID" parameterType='string' resultMap="BaseResultMap">
        select * from user where id=#{id}
    </select>

    <insert id="addUserInfo" parameterType="com.keer.mybatisdemo.pojo.User">
        insert into user (id,name,sex)values (#{id},#{name},#{sex})
    </insert>

    <update id="updateUserNameByID">
        update user set name=#{name} where id=#{id}
    </update>

    <delete id="deleteUserInfoByID">
        delete from user where id =#{id}
    </delete>

</mapper>

Create the mapper folder under the resource/mybatis folder, and put UserMapper.xml in this folder
And add the mapper file location in application.properties

mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

2.1.5 use examples

1.select query

 	@Autowired
    UserMapper userMapper;

    @Test
    @DisplayName("Get all user information")
    public void testGetAllUser() {
        System.out.println(userMapper.getAll().toString());
    }

	@Test
    @DisplayName("According to users id Get user information")
    public void testGetUserInfoByID() {
        Assert.assertEquals("Zhang",userMapper.getUserInfoByID("1").getName());
    }

2.insert

	@Test
    @DisplayName("Add user information")
    public void testAddUserInfo() {
        User user = new User("keer", "male", "2");
        Assert.assertEquals(1, userMapper.addUserInfo(user));
    }

3.update

	@Test
    @DisplayName("According to users id Update user name")
    public void testUpdateUserNameByID() {
        Assert.assertEquals(1,userMapper.updateUserNameByID("Co ear", "2"));
    }

4.delete

	@Test
    @DisplayName("According to users id Delete user information")
    public void testDeleteUserInfoByID() {
        Assert.assertEquals(1,userMapper.deleteUserInfoByID("2"));
    }

2.2 use notes

2.2.1 create people table

As shown in Figure 3:

2.1.2. Create People object class

As shown in Figure 4: create the corresponding member variables and add getter(),setter() and toString() methods

2.1.3 create mapper object

Show the information in xml by annotation
Replace the corresponding tags in the xml file by using the select,insert,update,delete annotations

public interface PeopleMapper {
    /**
     * Query all personal information
     * @return
     */
    @Select("select * from people")
    @Results({
            @Result(property = "id",column = "id"),
            @Result(property = "name",column = "name"),
            @Result(property = "age",column = "age"),
            @Result(property = "address",column = "address")
    })
    List<People> getAllPeopleInfo();

    /**
     * Query personal information according to id
     * @param id
     * @return
     */
    @Select("select * from people where id=#{id}")
    @Results({
            @Result(property = "id",column = "id"),
            @Result(property="name",column = "name"),
            @Result(property = "address",column = "address"),
            @Result(property = "age",column = "age")
    })
    People getPeopleInfoByID(int id);

    /**
     * Add personnel information
     * @param people
     * @return
     */
    @Insert("insert into people(id,name,address,age)values(#{id},#{name},#{address},#{age})")
    int addPeopleInfo(People people);

    /**
     * Change person name according to ID
     * @param name
     * @param id
     * @return
     */
    @Update("update people set name=#{name} where id = #{id}")
    int updatePeopleNameByID(String name,int id);

    /**
     * Delete personnel information according to ID
     * @param id
     * @return
     */
    @Delete("delete from people where id= #{id}")
    int deletePeopleInfoByID(int id);
}

At this time, you can add @ Mapper to the Mapper to scan the file. If there are many Mapper files, you can add the annotation MapperScan to the startup class to scan the entire Mapper folder.

@SpringBootApplication
@MapperScan("com.keer.mybatisdemo.mapper")
public class MybatisdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisdemoApplication.class, args);
    }
}

The method used is the same as that of xml, just call mapper directly. Not too much

28 original articles published, praised 4, 2121 visitors
Private letter follow

Keywords: Mybatis xml Spring MySQL

Added by jsscart on Mon, 09 Mar 2020 05:23:39 +0200