Learning Spring Boot: (7) Integrating Mybatis

I used spring data JPA in the front. Now I'm learning Mybatis, and now Mybatis also supports the annotation form like JPA, which is also very convenient. Let's learn it.

  • database mysql 5.7

add dependencies

In the pom file add:

<mybatis.version>1.3.1</mybatis.version>
<druid.version>1.1.3</druid.version>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.version}</version>
        </dependency>

As the tomcat-jdbc data source used by springboot by default, I added Alibaba's data source for convenience.

First understand what mybatis-spring-boot-starterwill be done:
* Automatically detect an existing DataSource
* Will create and register an instance of SqlSessionFactory that uses SqlSessionFactoryBean to pass that DataSource as input
* Will create and register an instance of SqlSessionTemplate obtained from SqlSessionFactory.
* Automatically scan your mappers, link them to the SqlSessionTemplate and register them with the Spring context so they can be injected into your beans.

As long as you use this springboot mybatis starter, you only need the configuration of the DataSource, and it will automatically create the SqlSessionFactoryBean and SqlSessionTemplate that use the DataSource. Your Mappers will be automatically scanned, connected to the SqlSessionTemplate, and registered with the Spring context.

Configure the data source

Add some data source connection parameter configuration to the resources/applicaiton.ymlfile (optional):

spring:
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.jdbc.Driver
        druid:
            url: jdbc:mysql://localhost:3306/learnboot?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
            username: root
            password: 123456
            initial-size: 10
            max-active: 100
            min-idle: 10
            max-wait: 60000
            pool-prepared-statements: true
            max-pool-prepared-statement-per-connection-size: 20
            time-between-eviction-runs-millis: 60000
            min-evictable-idle-time-millis: 300000
            validation-query: SELECT 1
            test-while-idle: true
            test-on-borrow: false
            test-on-return: false
            stat-view-servlet:
                enabled: true
                url-pattern: /druid/*
            filter:
                stat:
                    log-slow-sql: true
                    slow-sql-millis: 1000
                    merge-sql: true
                wall:
                    config:
                        multi-statement-allow: true

springboot will automatically load the spring.datasource.* related configuration, the data source will be automatically injected into the sqlSessionFactory, and the sqlSessionFactory will be automatically injected into the Mapper,

Using Mybatis

First I have one SysUser,

public class SysUserEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    //主键
    private Long id;
    //用户名
    @NotBlank(message = "用户名不能为空", groups = {AddGroup.class, UpdateGroup.class})
    private String username;
    //密码
    private String password;

Use the XML form

Let's create the User's mapping SysUserDao, and we can also name Mapper as a suffix. Here we write an interface to add a new piece of data. It should be noted that each Mapper class should be @Mapperannotated:

@Mapper
public interface SysUserDao {
    void save(SysUserEntity user);
    /**
     * 根据条件查询User
     * @param user User
     * @return 符合条件列表
     */
    List<SysUserEntity> query(SysUserEntity user);
}

When using xml, it should be noted that Mybatis scans mapper.xml and assembles it, which needs to be resources/applicaiton.ymladded to the system configuration file:

# Mybatis配置
mybatis:
    mapperLocations: classpath:mapper/**/*.xml
    configuration:
        map-underscore-to-camel-case: true

Configure according to your own xml directory.
For example: I resources/mapper/sysadd a file under the directory SysUserDao.xmland add the SQL we query:

<?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.wuwii.module.sys.dao.SysUserDao">

    <!-- 可根据自己的需求,是否要使用 -->
    <resultMap type="com.wuwii.module.sys.entity.SysUserEntity" id="sysUserMap">
        <result property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="password" column="password"/>
    </resultMap>

        <insert id="save" parameterType="com.wuwii.module.sys.entity.SysUserEntity" useGeneratedKeys="true"
            keyProperty="id">
        INSERT INTO sys_user
        (
            `username`,
            `password`
        )
        VALUES
            (
                #{username},
                #{password}
            )
    </insert>

    <select id="query" resultType="com.wuwii.module.sys.entity.SysUserEntity">
        SELECT *
        FROM sys_user
       <where>
           <if test="username != null"> and `username` = #{username}</if>
           <if test="password != null">and `password` = #{password}</if>
       </where>
    </select>

Use annotation form

This is much more convenient. There is no Mapper.xml file, and you don't need to configure the mapping of its file path. Just write the SQL in the xml to the annotation.
Change it directly SysUserDaoto:

@Mapper
public interface SysUserDao {
    @Insert("INSERT INTO sys_user(username,password) VALUES(#{username}, #{password})")
    void save(SysUserEntity user);

    @Select("SELECT * FROM sys_user WHERE id = #{id}")
    @Results({
        @Result(property = "username",  column = "username", javaType = String.class),
        @Result(property = "password", column = "password")
    })
    UserEntity getOne(Long id);
}

Different annotations are used according to different operations on the database:
* @Select is the annotation of the query class, all queries use this
* @Result to modify the returned result set, the associated entity class attributes and database fields correspond one by one, if the entity class The attribute name is the same as the database attribute name, so this attribute does not need to be modified.
* @Insert is inserted into the database for use, and directly passed in the entity class will automatically resolve the attribute to the corresponding value
* @Update is responsible for modification, or you can directly pass in the object
* @Delete is responsible for deletion

Note the difference between using the # symbol and the $ symbol:

// This example creates a prepared statement, something like select * from teacher where name = ?;
@Select("Select * from teacher where name = #{name}")
Teacher selectTeachForGivenName(@Param("name") String name);

// This example creates n inlined statement, something like select * from teacher where name = 'someName';
@Select("Select * from teacher where name = '${name}'")
Teacher selectTeachForGivenName(@Param("name") String name);

unit test

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class UserDaoTest {
    @Resource
    private SysUserDao userDao;

    @Test
    @Transactional
    @Rollback(false)
    public void testSave() {
        SysUserEntity user = new SysUserEntity();
        user.setUsername("wuwii");
        user.setPassword("123");
        userDao.save(user);
        Assert.assertEquals(user.getUsername(), userDao.query(user).get(0).getUsername());
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325632833&siteId=291194637