SpringBoot 整合 Mybatis 并使用idea插件生成实体类、mapper接口、xml文件
GitHub: link. 欢迎star
注意:本篇博客风格(不多比比就是撸代码!!!)
一、maven依赖
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
二、SpringbootMybatisApplication.java
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan({"com.andon.springbootmybatis.mapper"}) //扫描mapper接口文件所在包
@SpringBootApplication
public class SpringbootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisApplication.class, args);
}
}
三、application.yml
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8&autoReconnect=true&failOverReadOnly=false
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
mybatis:
configuration:
call-setters-on-nulls: true # 不忽略查询结果为null的字段
mapper-locations: classpath:mapperxml/*Mapper.xml # mapper接口对应xml文件所在包位置
四、执行sql新建测试表
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for test_table
-- ----------------------------
DROP TABLE IF EXISTS `test_table`;
CREATE TABLE `test_table` (
`id` int(0) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`key` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'key',
`value` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'value',
`update_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间',
`create_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '测试表' ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
五、Idea 插件 MyBatisCodeHelperPro 生成 实体类、mapper接口、xml文件
1.插件MyBatisCodeHelperPro
2.连接Database
3.生成代码
六、生成的代码
1.TestTable.java
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author Andon
* 2021/11/17
*/
@ApiModel(value="测试表")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TestTable implements Serializable {
/**
* ID
*/
@ApiModelProperty(value="ID")
private Integer id;
/**
* key
*/
@ApiModelProperty(value="key")
private String key;
/**
* value
*/
@ApiModelProperty(value="value")
private String value;
/**
* 更新时间
*/
@ApiModelProperty(value="更新时间")
private Date updateTime;
/**
* 创建时间
*/
@ApiModelProperty(value="创建时间")
private Date createTime;
private static final long serialVersionUID = 1L;
}
2.TestTableMapper.java
import com.andon.springbootmybatis.domain.TestTable;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author Andon
* 2021/11/17
*/
public interface TestTableMapper {
/**
* 自动生成
*/
int deleteByPrimaryKey(Integer id);
int insert(TestTable record);
int insertSelective(TestTable record);
TestTable selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(TestTable record);
int updateByPrimaryKey(TestTable record);
/**
* 自定义
*/
int insertTestTableBatch(@Param("testTableList") List<TestTable> testTableList);
List<TestTable> selectTestTable(@Param("row") int row, @Param("size") int size);
List<TestTable> selectTestTableLikeKey(@Param("key") String key, @Param("row") int row, @Param("size") int size);
List<TestTable> selectTestTableSelective(@Param("idList") List<Integer> idList, @Param("key") String key, @Param("row") int row, @Param("size") int size);
}
3.TestTableMapper.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.andon.springbootmybatis.mapper.TestTableMapper">
<resultMap id="BaseResultMap" type="com.andon.springbootmybatis.domain.TestTable">
<!--@mbg.generated-->
<!--@Table test_table-->
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="key" jdbcType="VARCHAR" property="key"/>
<result column="value" jdbcType="VARCHAR" property="value"/>
<!-- <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>-->
<!-- <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>-->
</resultMap>
<sql id="Base_Column_List">
<!--@mbg.generated-->
id, `key`, `value`, update_time, create_time
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
<!--@mbg.generated-->
select
<include refid="Base_Column_List"/>
from test_table
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
<!--@mbg.generated-->
delete
from test_table
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.andon.springbootmybatis.domain.TestTable"
useGeneratedKeys="true">
<!--@mbg.generated-->
insert into test_table (`key`, `value`, update_time,
create_time)
values (#{key,jdbcType=VARCHAR}, #{value,jdbcType=VARCHAR}, #{updateTime,jdbcType=TIMESTAMP},
#{createTime,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" keyColumn="id" keyProperty="id"
parameterType="com.andon.springbootmybatis.domain.TestTable" useGeneratedKeys="true">
<!--@mbg.generated-->
insert into test_table
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="key != null">
`key`,
</if>
<if test="value != null">
`value`,
</if>
<if test="updateTime != null">
update_time,
</if>
<if test="createTime != null">
create_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="key != null">
#{key,jdbcType=VARCHAR},
</if>
<if test="value != null">
#{value,jdbcType=VARCHAR},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=TIMESTAMP},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.andon.springbootmybatis.domain.TestTable">
<!--@mbg.generated-->
update test_table
<set>
<if test="key != null">
`key` = #{key,jdbcType=VARCHAR},
</if>
<if test="value != null">
`value` = #{value,jdbcType=VARCHAR},
</if>
<if test="updateTime != null">
update_time = #{updateTime,jdbcType=TIMESTAMP},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.andon.springbootmybatis.domain.TestTable">
<!--@mbg.generated-->
update test_table
set `key` = #{key,jdbcType=VARCHAR},
`value` = #{value,jdbcType=VARCHAR},
update_time = #{updateTime,jdbcType=TIMESTAMP},
create_time = #{createTime,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>
<insert id="insertTestTableBatch">
INSERT INTO `test_table` (`key`, `value`)
VALUES
<foreach collection="testTableList" item="testTable" separator=",">
(#{testTable.key,jdbcType=VARCHAR}, #{testTable.value,jdbcType=VARCHAR})
</foreach>
</insert>
<select id="selectTestTable" resultMap="BaseResultMap">
SELECT `id`, `key`, `value`, `update_time` AS `updateTime`, `create_time` AS `createTime`
FROM `test_table`
ORDER BY `update_time` DESC
LIMIT #{row},#{size}
</select>
<select id="selectTestTableLikeKey" resultMap="BaseResultMap">
SELECT `id`, `key`, `value`, `update_time` AS `updateTime`, `create_time` AS `createTime`
FROM `test_table`
WHERE `key` LIKE CONCAT('%', #{key,jdbcType=VARCHAR}, '%')
ORDER BY `update_time` DESC
LIMIT #{row},#{size}
</select>
<select id="selectTestTableSelective" resultMap="BaseResultMap">
SELECT `id`, `key`, `value`, `update_time` AS `updateTime`, `create_time` AS `createTime`
FROM `test_table`
<where>
<if test="idList != null and idList.size() != 0">
`id` IN
<foreach collection="idList" item="id" index="index" open="(" close=")" separator=",">
#{id,jdbcType=INTEGER}
</foreach>
</if>
<if test="key != null and key != ''">
AND `key` LIKE CONCAT('%', #{key,jdbcType=VARCHAR}, '%')
</if>
</where>
ORDER BY `update_time` DESC
LIMIT #{row},#{size}
</select>
</mapper>
七、DatabaseTest.java
import com.alibaba.fastjson.JSONObject;
import com.andon.springbootmybatis.domain.TestTable;
import com.andon.springbootmybatis.mapper.TestTableMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
/**
* @author Andon
* 2021/11/17
*/
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class DatabaseTest {
@Resource
private TestTableMapper testTableMapper;
@Test
public void test02() {
TestTable testTable = testTableMapper.selectByPrimaryKey(1);
log.info("testTable:{}", JSONObject.toJSONString(testTable));
}
@Test
public void test01() {
TestTable testTable = TestTable.builder().key("hello").value("world").build();
int row = testTableMapper.insertSelective(testTable);
log.info("row:{}", row);
}
}
八、测试
GitHub: link. 欢迎star