SpringBoot Two Ways to Simply Integrate Mybatis

Posted by Good2CU on Mon, 12 Aug 2019 10:29:14 +0200

rely on

Be careful
The database connection pool is used here, the Druid is used here, and the Druid is used here is com.alibaba.druid-spring-boot-starter. The starter is provided by a third party. The names of MyBatis and Druid depend on are different from those of other libraries, but the mysql it supports is mysql 8, because of the database version problem. So we need to lock the database version.

The dependencies we need here

<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.0.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.28</version>
    <scope>runtime</scope>
</dependency>

application.properties

spring.datasource.one.url=jdbc:mysql:///db?useUnicode=true&characterEncoding=utf-8
spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.one.username=root
spring.datasource.one.password=rootzsl

Mapper interface

public interface EmpMapper {
    List<User> getAllEmp ();

    Integer addUser(Emp emp);

    Integer updateEmpById(Emp emp);

    Integer deleteEmpById(Integer id);
}

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.zsl.mybatis02.mapper1.IMapperOne">
    <select id="getAllEmp" resultType="com.zsl.mybatis02.pojo.Emp">
        select * from emp;
    </select>

    <insert id="addEmp" parameterType="com.zsl.mybatis02.pojo.Emp">
        insert into emp (username,address) values (#{username},#{address});
    </insert>

    <update id="updateEmpById" parameterType="com.zsl.mybatis02.pojo.Emp">
        update user set emp=#{username},address=#{address} where id=#{id}
    </update>
    
    <delete id="deleteEmpById">
        delete from emp where id=#{id}
    </delete>

</mapper>

About the location of this Mapper.xml
Here are two kinds:
1.xml configuration files and interfaces are under one package.
2. The XML configuration file is in the mapper directory under the resources directory

xml configuration files and interfaces can be scanned by containers under a package, but they are ignored when packaged and cannot be packaged directly.

Solution:
Add the following configuration to the pom.xml file to avoid automatically ignoring the XML files in the java directory when packaging.

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
</build>

xml configuration files in the mapper directory under the resources directory, packaging will not be ignored, but the container can not be scanned automatically, we need to configure in the configuration file.

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

In fact, there is an unusual way to write sql without using xml configuration files and using annotations.
Add annotations and corresponding sql statements directly to the mapper interface

@Repository
public interface IMapperOne {

    List<Emp> getAllEmp();



    @Select("select * from emp")
    List<Emp> getAllEmp();

    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "ename", column = "e"),
            @Result(property = "address", column = "a")
    })
    @Select("select ename as e,address as a,id as id from emp where id=#{id}")
    Emp getEmpById(Long id);

    @Select("select * from emp where ename like concat('%',#{name},'%')")
    List<User> getEmpByName(String name);

    @Insert({"insert into emp(ename,address) values(#{ename},#{address})"})
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Integer.class)
    Integer addEmp(Emp emp);

    @Update("update emp set ename=#{ename},address=#{address} where id=#{id}")
    Integer updateEmpById(Emp emp);

    @Delete("delete from emp where id=#{id}")
    Integer deleteEmpById(Integer id);
    
}

SQL is written by full annotation instead of XML file. The annotations @Select, @Insert, @Update and @Delete correspond to the select, insert, update and delete tags in XML respectively.
And @Results corresponds to the ResultMap mapping file in xml.
It is worth mentioning that the @SelectKey annotation can achieve the function of backfilling the primary key, which is to get the primary key of the data when you add a new ratio of data.

Using full annotation to write SQL instead of XML file, we need to specify mapper scanning path. There are two ways:
1. Add scan annotation @Mapper to each mapper interface
2. Simply configure the mapper scan annotation on the startup class to specify which package it will scan under

@SpringBootApplication
@MapperScan(basePackages = "com.zsl.mybatis02.mapper1")
public class MybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}

Topics: xml Spring Mybatis Druid