Spring Boot 2.X learning diary -- integrating mybatis

Article directory


Mybatis is the most frequently used ORM framework in our normal development. This section is mainly based on the official Starter provided by mybatis for integration.

Preparation

Environmental Science

  • mysql 5.5+

First of all, we need to add a t ﹣ notice table to the database

init.sql

CREATE TABLE `t_notice` (
  `id` varchar(36) NOT NULL COMMENT 'Logical primary key',
  `context` varchar(200) DEFAULT NULL COMMENT 'Announcement content',
  `sort` int(11) DEFAULT NULL COMMENT 'sort',
  `is_use` int(11) DEFAULT NULL COMMENT '0--Available 1--Unavailable',
  `create_time` datetime DEFAULT NULL COMMENT 'Creation time',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Second, we need to integrate the necessary jar packages

    //Database dependency
    compile 'org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2'
    compile 'mysql:mysql-connector-java:5.1.40'

    //unit testing
    testCompile 'org.springframework.boot:spring-boot-starter-test'

Use

  1. Modify application.yml

    application.yml

    mybatis:
      mapper-locations: classpath*:mapper/*Mapper.xml #xml file to scan
    spring:
      datasource:
        url: jdbc:mysql://{Database address}/{Database name}?useUnicode=true&characterEncoding=utf-8
        username: {Database login}
        password: {Database password} #If not, delete it
        driver-class-name: com.mysql.jdbc.Driver
    
  2. Add NoticeService.java,NoticeMapper.java,Notice.java under src/main/java

    NoticeService.java

    package com.boot.demo.service;
    
    import com.boot.demo.entity.Notice;
    import com.boot.demo.mapper.NoticeMapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.List;
    import java.util.UUID;
    
    @Service
    public class NoticeService {
    
        @Autowired
        private NoticeMapper noticeMapper;
    
        public List<Notice> getList(){
            return noticeMapper.getList();
        }
    
        @Transactional
        public void save(Notice notice){
            String noticeId = notice.getId();
            if(null != noticeId && "" != noticeId){
                noticeMapper.updateNotice(notice);
            } else {
                notice.setId(UUID.randomUUID().toString());
                noticeMapper.insertNotice(notice);
            }
        }
    
        @Transactional
        public void remove(String id){
            noticeMapper.removeNotice(id);
        }
    }
    

    NoticeMapper.java

    package com.boot.demo.mapper;
    
    import com.boot.demo.entity.Notice;
    import org.apache.ibatis.annotations.Mapper;
    
    import java.util.List;
    
    @Mapper
    public interface NoticeMapper {
    
        //Get list
        List<Notice> getList();
    
        //Newly added
        void insertNotice(Notice notice);
    
        //To update
        void updateNotice(Notice notice);
    
        //delete
        void removeNotice(String id);
    }
    

    Notice.java

    package com.boot.demo.entity;
    
    import java.util.Date;
    
    public class Notice {
    
        private String id;
    
        private String context;
    
        private Integer sort;
    
        private Byte isUse;
    
        private Date createTime;
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getContext() {
            return context;
        }
    
        public void setContext(String context) {
            this.context = context;
        }
    
        public Integer getSort() {
            return sort;
        }
    
        public void setSort(Integer sort) {
            this.sort = sort;
        }
    
        public Byte getIsUse() {
            return isUse;
        }
    
        public void setIsUse(Byte isUse) {
            this.isUse = isUse;
        }
    
        public Date getCreateTime() {
            return createTime;
        }
    
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
    }
    
  3. Add mapper folder under src/main/resources, and add NoticeMapper.xml

    NoticeMapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.boot.demo.mapper.NoticeMapper">
        <resultMap id="notice" type="com.boot.demo.entity.Notice">
            <id column="id" property="id" javaType="string"/>
            <result column="context" property="context" javaType="string"/>
            <result column="sort" property="sort" javaType="int"/>
            <result column="is_use" property="isUse" javaType="byte" />
            <result column="create_time" property="createTime" javaType="java.util.Date"/>
        </resultMap>
        <select id="getList" resultMap="notice">
            select
              id,
              context,
              sort,
              is_use,
              create_time
            FROM
              t_notice
        </select>
    
        <insert id="insertNotice" parameterType="com.boot.demo.entity.Notice">
            insert into t_notice
                <trim prefix="(" suffix=")" suffixOverrides=",">
                    <if test="null != id and '' != id">
                        id,
                    </if>
                    <if test="null != context and '' != context">
                        context,
                    </if>
                    <if test="null != sort">
                        sort,
                    </if>
                    <if test="null != isUse">
                        is_use,
                    </if>
                    create_time
                </trim>
                <trim prefix="values (" suffix=")" suffixOverrides=",">
                    <if test="null != id and '' != id">
                        #{id},
                    </if>
                    <if test="null != context and '' != context">
                        #{context},
                    </if>
                    <if test="null != sort">
                        #{sort},
                    </if>
                    <if test="null != isUse">
                        #{isUse},
                    </if>
                    now()
                </trim>
        </insert>
    
        <update id="updateNotice" parameterType="com.boot.demo.entity.Notice">
            update t_notice
            <set>
                <if test="null != context and '' != context">
                    context = #{context},
                </if>
                <if test="null != sort">
                    sort = #{sort},
                </if>
                <if test="null != isUse">
                    is_use =#{isUse},
                </if>
            </set>
            where id = #{id}
        </update>
    
        <delete id="removeNotice" parameterType="string">
            delete from t_notice where id = #{id}
        </delete>
    </mapper>
    
  4. Add a new test class NoticeTest.java under src/test/java

    NoticeTest.java

    package com.boot.demo.test;
    
    import com.boot.demo.entity.Notice;
    import com.boot.demo.service.NoticeService;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.util.List;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest(properties = "spring.main.web-application-type=reactive")
    public class NoticeTest {
    
        private static final Logger logger = LoggerFactory.getLogger(NoticeTest.class);
    
        @Autowired
        private NoticeService noticeService;
    
        @Test
        public void getNoticeListTest(){
            ObjectMapper objectMapper = new ObjectMapper();
            List<Notice> notices = noticeService.getList();
            for(Notice notice : notices){
                try {
                    logger.info(objectMapper.writeValueAsString(notice));
                } catch (JsonProcessingException e) {
                    logger.error(e.getMessage(),e);
                }
            }
        }
    
        @Test
        public void addNotice(){
            //Newly added
            Notice notice = new Notice();
            notice.setContext("Ha ha Da");
            notice.setSort(0);
            noticeService.save(notice);
        }
    
        @Test
        public void updateNotice(){
            Notice notice = new Notice();
            notice.setId("noticeId");   //Replace the noticeId with the record id of the action required
            notice.setIsUse((byte)1);
            noticeService.save(notice);
        }
    
        @Test
        public void removeNotice(){
            noticeService.remove("noticeId"); //Replace the noticeId with the record id of the action required
        }
    }
    

Well, here, the Spring Boot integration of mybatis is over. Dear readers, you can test whether the integration is completed by running the above test classes.

Full text code

Say a sentence

The above content is designed based on the readers who have used mybatis. If the syntax of mybatis is not clear, the document address of mybatis will be attached at the end of this article. Readers can consult it by themselves.

Official documents of mybatis

Tags: Java Mybatis Database Spring

Posted on Sun, 01 Dec 2019 17:39:42 -0800 by adt2007