Spring CLoud 整合通用Mapper+Lombok+Mysql
文章目录
- 一、使用Spring Initializr快速创建Spring Boot应用
- 二、相关依赖
- 2.1. 添加依赖
- 2.2. mybatis添加插件
- 2.3. 在resources目录下面创建generator目录存放generatorConfig.xml
- 2.3.1. config.properties配置文件
- 2.3.2. lombok插件
- 2.3.3. 数据库信息
- 2.3.4. 代码生成实体类、mapper接口和mapper.xml
- 2.3.5. 指定生成那些表
- 2.4. config.properties配置文件
- 2.4.1. 数据库信息
- 2.4.2. 模块名称
- 2.4.3. 表名
- 2.5. 配置SpringBoot配置文件
- 2.6. 运行数据库脚本
- 2.7. 双击运行:
- 三、代码生成效果
- 3.1. 实体类效果:
- 3.2. mapper接口效果:
- 3.3. mapper映射文件效果:
- 四、启动类添加注解
- 五、单元测试
- 六、发布一个list端点,进行web服务调用
- 6.2. 调用服务截图
一、使用Spring Initializr快速创建Spring Boot应用
也可以都不选
创建项目完成!!!
二、相关依赖
2.1. 添加依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--通用mapper--><dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spring-boot-starter</artifactId><version>2.1.5</version></dependency><!--Lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.8</version><scope>provided</scope></dependency><!-- mysql 驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!-- 单元测试--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>
2.2. mybatis添加插件
<plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1.3.6</version><configuration><configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile><overwrite>true</overwrite><verbose>true</verbose></configuration><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.16</version></dependency><!-- https://mvnrepository.com/artifact/tk.mybatis/mapper --><dependency><groupId>tk.mybatis</groupId><artifactId>mapper</artifactId><version>4.1.5</version></dependency></dependencies></plugin>
2.3. 在resources目录下面创建generator目录存放generatorConfig.xml
- 涉及以下5部分:
2.3.1. config.properties配置文件
2.3.2. lombok插件
2.3.3. 数据库信息
2.3.4. 代码生成实体类、mapper接口和mapper.xml
2.3.5. 指定生成那些表
generatorConfig.xml文件内容如下:
<!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><properties resource="generator/config.properties"/><context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat"><property name="beginningDelimiter" value="`"/><property name="endingDelimiter" value="`"/><plugin type="tk.mybatis.mapper.generator.MapperPlugin"><property name="mappers" value="tk.mybatis.mapper.common.Mapper"/><property name="caseSensitive" value="true"/><property name="lombok" value="Getter,Setter,ToString"/></plugin><jdbcConnection driverClass="${jdbc.driverClass}"connectionURL="${jdbc.url}"userId="${jdbc.user}"password="${jdbc.password}"></jdbcConnection><!--实体--><javaModelGenerator targetPackage="com.gblfy.springboot.mapper.lombok.mysql.domain.entity.${moduleName}"targetProject="src/main/java"/><!--mapper.xml--><sqlMapGenerator targetPackage="com.gblfy.springboot.mapper.lombok.mysql.dao.${moduleName}"targetProject="src/main/resources"/><!--mapper接口--><javaClientGenerator targetPackage="com.gblfy.springboot.mapper.lombok.mysql.dao.${moduleName}"targetProject="src/main/java"type="XMLMAPPER"/><!--为哪张表生成代码--><table tableName="${tableName}"><generatedKey column="id" sqlStatement="JDBC"/></table></context>
</generatorConfiguration>
2.4. config.properties配置文件
涉及部分:
2.4.1. 数据库信息
2.4.2. 模块名称
2.4.3. 表名
具体内容:
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mapperlombok?nullCatalogMeansCurrent=true
jdbc.user=root
jdbc.password=root#模块名称
moduleName=content#表名
tableName=user
2.5. 配置SpringBoot配置文件
#数据库信息
spring:datasource:url: jdbc:mysql://localhost:3306/mapperlombokdriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: root
# 应用名称application:name: content-center
# 应用启动端口
server:port: 8080
2.6. 运行数据库脚本
CREATE TABLE `user` (`user_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',`account` varchar(45) COLLATE utf8_bin DEFAULT NULL COMMENT '账号',`password` varchar(45) COLLATE utf8_bin DEFAULT NULL COMMENT '密码',`create_time` datetime DEFAULT NULL COMMENT '创建时间',`update_time` datetime DEFAULT NULL COMMENT '更新时间',PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_bin ROW_FORMAT=DYNAMIC COMMENT='用户表';
2.7. 双击运行:
三、代码生成效果
3.1. 实体类效果:
package com.gblfy.springboot.mapper.lombok.mysql.domain.entity.content;import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Table(name = "user")
public class User {/*** 主键id*/@Id@Column(name = "user_id")private Long userId;/*** 账号*/private String account;/*** 密码*/private String password;/*** 创建时间*/@Column(name = "create_time")private Date createTime;/*** 更新时间*/@Column(name = "update_time")private Date updateTime;
}
3.2. mapper接口效果:
package com.gblfy.springboot.mapper.lombok.mysql.dao.content;import com.gblfy.springboot.mapper.lombok.mysql.domain.entity.content.Order;
import tk.mybatis.mapper.common.Mapper;public interface UserMapper extends Mapper<User> {
}
3.3. mapper映射文件效果:
<?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.gblfy.springboot.mapper.lombok.mysql.dao.content.UserMapper"><resultMap id="BaseResultMap" type="com.gblfy.springboot.mapper.lombok.mysql.domain.entity.content.User"><!--WARNING - @mbg.generated--><id column="user_id" jdbcType="BIGINT" property="userId" /><result column="account" jdbcType="VARCHAR" property="account" /><result column="password" jdbcType="VARCHAR" property="password" /><result column="create_time" jdbcType="TIMESTAMP" property="createTime" /><result column="update_time" jdbcType="TIMESTAMP" property="updateTime" /></resultMap>
</mapper>
四、启动类添加注解
– 不然spring扫描不到,无法将mapper进行实例化,导致mapper接口无法注入
@SpringBootApplication
@MapperScan("com.gblfy.springboot.mapper.lombok.mysql")
public class SpringbootMapperLombokMysqlApplication {public static void main(String[] args) {SpringApplication.run(SpringbootMapperLombokMysqlApplication.class, args);}
}
五、单元测试
package com.gblfy.springboot.mapper.lombok.mysql.dao.content;import com.gblfy.springboot.mapper.lombok.mysql.SpringbootMapperLombokMysqlApplicationTests;
import com.gblfy.springboot.mapper.lombok.mysql.domain.entity.content.User;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.stereotype.Component;import javax.annotation.Resource;
import java.util.Date;
import java.util.List;@Component
@Slf4j
public class SysUserMapperTest extends SpringbootMapperLombokMysqlApplicationTests {@Resourceprivate UserMapper userMapper;/*** 插入数据并查询用户列表*/@Testpublic void insertAndSelect() {//插入用户数据User user = User.builder().account("gblfy").password("123").createTime(new Date()).updateTime(new Date()).build();int i = this.userMapper.insertSelective(user);//查询用户列表List<User> userList = this.userMapper.selectAll();//断言数据库数据条数为1条,如不是1条则,控制台异常提示Assert.assertEquals(1, userList.size());//循环遍历用户列表for (User u : userList) {log.info("用户列表信息={}", u.toString());}}
}
六、发布一个list端点,进行web服务调用
package com.gblfy.springboot.mapper.lombok.mysql.controller.content;import com.gblfy.springboot.mapper.lombok.mysql.dao.content.UserMapper;
import com.gblfy.springboot.mapper.lombok.mysql.domain.entity.content.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.Date;
import java.util.List;/*** @author gblfy* @ClassNme UserController* @Description TODO* @Date 2019/7/7 19:09* @version1.0*/
@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserController {private final UserMapper userMapper;@RequestMapping("/list")public List<User> insertAndSelect() {//插入用户数据User user = User.builder().account("gblfy").password("123").createTime(new Date()).updateTime(new Date()).build();int i = this.userMapper.insertSelective(user);log.info("插入用户信息成功={}", i);//查询用户列表List<User> userList = this.userMapper.selectAll();log.info("查询用户列表信息成功");return userList;}
}
6.2. 调用服务截图
调用服务地址:http://localhost:8080/user/list
本文下载链接:
Github地址:https://github.com/gb-heima/springboot-mapper-lombok-mysql
zip包下载链接:
https://codeload.github.com/gb-heima/springboot-mapper-lombok-mysql/zip/master