SpringBoot learning path -- integrating Mybatis with SpringBoot

1, Basic environment preparation

1. Create a new query in Navicat, create the database develop ment, and create two tables t in the library_ Article and t_comment, just run the following script

#Create database

CREATE DATABASE develop;

#Select Use Database

USE develop;

#Create table t_article and insert relevant data

DROP TABLE IF EXISTS t_article; CREATE TABLE t_article ( id int(20) NOT NULL AUTO_INCREMENT COMMENT 'article id', title varchar(200) DEFAULT NULL COMMENT 'Article title', content longtext COMMENT 'Article content', PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; INSERT INTO t_article VALUES ('1', 'Spring Boot Basic introduction', 'From introduction to mastery...'); INSERT INTO t_article VALUES ('2', 'Spring Cloud Basic introduction', 'From introduction to mastery...');

#Create table t_comment and insert relevant data

DROP TABLE IF EXISTS t_comment; CREATE TABLE t_comment ( id int(20) NOT NULL AUTO_INCREMENT COMMENT 'comment id', content longtext COMMENT 'Comment content', author varchar(200) DEFAULT NULL COMMENT 'Comment author', a_id int(20) DEFAULT NULL COMMENT 'Associated articles id', PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; INSERT INTO t_comment VALUES ('1', 'Very comprehensive and detailed', 'Niuniu is not afraid of difficulties', '1'); INSERT INTO t_comment VALUES ('2', 'Like one', 'Tom', '1'); INSERT INTO t_comment VALUES ('3', 'Very detailed', 'Kitty', '1'); INSERT INTO t_comment VALUES ('4', 'Very good, very detailed', 'Zhang San', '1'); INSERT INTO t_comment VALUES ('5', 'Very good', 'Lisa', '2');

2. In the project pom.xml, the related dependency initiators of Mysql and Mybatis are introduced

<!-- Mybatis starter-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- Mysql drive -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.49</version>
</dependency>
<!-- Druid data source  -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

3. Write the entity class corresponding to the database table

import java.util.List;
​
public class Article {
    private Integer id;
    private String  title;
    private String  Content;
    private List<Comment> commentList;
    //Omit setter and getter methods
    //Omit the toString method
}
public class Comment {
    private Integer id;
    private String content;
    private String author;
    private Integer aId;
    //Omit setter and getter methods
    //Omit the toString method
}

4. Write the application.properties configuration file to connect the database and data source information

#Configure Mysql database information
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/develop?useUnicode=true&amp;characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
​
#Configure Druid information for third-party data sources
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize=20
spring.datasource.minIdle=10
spring.datasource.maxActive=100

5. Create a DataSourceConfig custom configuration class under src/main/java/com/chen/config package to inject the attribute value of the Druid data source

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
​
import javax.sql.DataSource;
​
@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource getDruid(){
        return new DruidDataSource();
    }
}

2, Integrating Mybatis with annotations

1. Create a mapper package under src/main/java/com/chen and create the mapper interface file CommentMapper class

import com.chen.domain.Comment;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;
​
@Mapper// It indicates that this class is a Mybatis interface file, which is automatically scanned into the Spring container by SpringBoot
@Component
public interface CommentMapper {
    @Select("select * from t_comment where id=#{id} ") / / query comments
    public Comment findByID(Integer id);
​
    @Insert("insert into t_comment(content,author,a_id) values(#{content},#{author},#{aId}) ") / / insert comment
    public int insertComment(Comment comment);
​
    @Delete("delete from t_comment where id=#{id} ") / / delete annotation
    public int deleteComment(Integer id);
​
    @Update("update t_comment set content=#{content} where id=#{id} ") / / update comments
    public int updateComment(Comment comment);
}

mapper class description

It is indicated by @ Mapper that this class is a Mapper interface file

You can also directly annotate @ MapperScan("com.chen.mapper") on the startup class, uniformly configure and identify the package path where the mapper interface file is located (avoid the trouble of configuring @ mapper annotation one interface file by one when there are multiple mapper files)

Use @ Select, @ Insert, @ Delete, @ Update annotations inside the class to complete the operations of adding, deleting, modifying and querying database tables with SQL statements

2. Create a test class to test the use of the interface

import com.chen.domain.Comment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
​
@RunWith(SpringRunner.class)
@SpringBootTest
public class MapperTest {
    @Autowired
    private CommentMapper commentMapper;
​
    @Test
    public void findComment(){
        Comment comment = commentMapper.findByID(2);
        System.out.println(comment);
    }
}

3. Run test class

From the results, we can see that the data has been found, but the aId is null. Let's see that the database table has value

ORM failed to map this value because the hump naming rule is not enabled, so you only need to enable the hump naming rule in application.properties

#Open hump naming
mybatis.configuration.map-underscore-to-camel-case=true

Run the test class again

3, Integrate Mybatis by using configuration files (commonly used in actual development)

1. Create Mapper interface file in src/main/java/com/chen/mapper

import com.chen.domain.Article;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
​
@Mapper
@Component
public interface ArticleMapper {
    public Article selectArticle(Integer id);
    public int updateArticle(Article article);
}

2. Create a new mapper package in the resource directory and create an xml Mapping configuration file

<?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.chen.mapper.ArticleMapper">
    <!-- 1,Query article details (including comments) -->
    <select id="selectArticle" resultMap="articleWithComment">
       SELECT a.*,c.id c_id,c.content c_content,c.author
       FROM t_article a,t_comment c
       WHERE a.id=c.a_id AND a.id = #{id}
    </select>
    <resultMap id="articleWithComment" type="Article">
        <id property="id" column="id" />
        <result property="title" column="title" />
        <result property="content" column="content" />
        <collection property="commentList" ofType="Comment">
            <id property="id" column="c_id" />
            <result property="content" column="c_content" />
            <result property="author" column="author" />
        </collection>
    </resultMap>
​
    <!-- 2,According to the article id Update article information -->
    <!--parameterType If you do not have the full path name of the class and use an alias, you need to configure the alias mapping path of the entity class in the global configuration file-->
    <update id="updateArticle" parameterType="Article" >
        UPDATE t_article
        <set>
            <if test="title !=null and title !=''">
                title=#{title},
            </if>
            <if test="content !=null and content !=''">
                content=#{content}
            </if>
        </set>
        WHERE id=#{id}
    </update>
</mapper>

xml Mapping File Description: the namespace attribute value uses the full path name of the interface file Mapper (note that it cannot be omitted)

3. Configure XML Mapping file path

#Configure the xml configuration file path for Mybatis
mybatis.mapper-locations=classpath:mapper/*.xml
#Configure the entity class alias path specified in the xml Mapping file
mybatis.type-aliases-package=com.chen.domain

4. Writing test classes

import com.chen.domain.Article;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
​
@RunWith(SpringRunner.class)
@SpringBootTest
public class MapperAndXMLTest {
    @Autowired
    private ArticleMapper articleMapper;
​
    @Test
    public void selectArticle(){
        Article article = articleMapper.selectArticle(1);
        System.out.println(article);
    }
}

5. debug runs the test class to view the data

 

It can be seen that selectArticle() is executed successfully, the article details with Article id 1 are queried, and the corresponding comment information is queried by association.

Tags: Java Maven Spring Boot

Posted on Wed, 24 Nov 2021 10:18:49 -0500 by natman3