Spring Boot 集成 TkMyBatis
原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/13196831.html
Project Directory
Maven Dependency
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.8.RELEASE</version> <relativePath/> </parent> <modelVersion>4.0.0</modelVersion> <groupId>org.fool.redis</groupId> <artifactId>redis-string-mybatis</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--pagehelper--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.13</version> </dependency> <!--mybatis--> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>4.1.5</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.4.0</version> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.22</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <configurationFile>sql/generatorConfig.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>4.1.5</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>
sql
schema.sql
CREATE TABLE `tb_user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL DEFAULT '' COMMENT '用户名', `password` varchar(50) NOT NULL DEFAULT '' COMMENT '密码', `sex` tinyint(4) NOT NULL DEFAULT '0' COMMENT '性别 0=女 1=男 ', `is_deleted` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '删除标志,默认0不删除,1删除', `create_time` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '创建时间', `update_time` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3) COMMENT '更新时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <classPathEntry location="/Users/${user.name}/.m2/repository/mysql/mysql-connector-java/5.1.49/mysql-connector-java-5.1.49.jar"/> <context id="mysql" targetRuntime="MyBatis3"> <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/> <plugin type="tk.mybatis.mapper.generator.MapperPlugin"> <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/> <property name="caseSensitive" value="true"/> </plugin> <commentGenerator> <property name="suppressAllComments" value="true"/> </commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="123456"> </jdbcConnection> <javaModelGenerator targetPackage="org.fool.redis.model" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <javaClientGenerator targetPackage="org.fool.redis.mapper" targetProject="src/main/java" type="XMLMAPPER"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <table tableName="tb_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration>
src/main/resources
application.properties
spring.application.name=redis-spring-mybatis server.port=8888 logging.level.org.fool.redis=debug mybatis.mapper-locations=classpath:mapper/**/*.xml spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useLegacyDatetimeCode=false spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.druid.initial-size=5 spring.datasource.druid.max-active=50 spring.datasource.druid.min-idle=5 spring.datasource.druid.max-wait=60000 spring.datasource.druid.min-evictable-idle-time-millis=300000 spring.datasource.druid.validation-query=SELECT 1 FROM DUAL spring.datasource.druid.test-while-idle=true spring.datasource.druid.test-on-borrow=false spring.datasource.druid.test-on-return=false spring.datasource.druid.filters=stat,wall spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 spring.datasource.druid.use-global-data-source-stat=true spring.redis.host=localhost spring.redis.port=6379 spring.redis.database=0 spring.redis.password= spring.redis.timeout=2000 spring.redis.pool.max-active=10 spring.redis.pool.max-wait=1000 spring.redis.pool.max-idle=10 spring.redis.pool.min-idle=5 spring.redis.pool.num-tests-per-eviction-run=1024 spring.redis.pool.time-between-eviction-runs-millis=30000 spring.redis.pool.min-evictable-idle-time-millis=60000 spring.redis.pool.soft-min-evictable-idle-time-millis=10000 spring.redis.pool.test-on-borrow=true spring.redis.pool.test-while-idle=true spring.redis.pool.block-when-exhausted=false
UserMapper.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="org.fool.redis.mapper.UserMapper"> <resultMap id="BaseResultMap" type="org.fool.redis.model.User"> <!-- WARNING - @mbg.generated --> <id column="id" jdbcType="INTEGER" property="id" /> <result column="username" jdbcType="VARCHAR" property="username" /> <result column="password" jdbcType="VARCHAR" property="password" /> <result column="sex" jdbcType="TINYINT" property="sex" /> <result column="is_deleted" jdbcType="BIT" property="isDeleted" /> <result column="create_time" jdbcType="TIMESTAMP" property="createTime" /> <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" /> </resultMap> <sql id="Base_Column_List"> <!-- WARNING - @mbg.generated --> id, username, password, sex, is_deleted, create_time, update_time </sql> </mapper>
Note: UserMapper.xml 是通过插件 mybatis-generator-maven-plugin 执行命令 mybatis-generator:generate -e 生成
src/main/java
application.java
1 package org.fool.redis; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 import tk.mybatis.spring.annotation.MapperScan; 6 7 @SpringBootApplication 8 @MapperScan("org.fool.redis.mapper") 9 public class Application { 10 public static void main(String[] args) { 11 SpringApplication.run(Application.class, args); 12 } 13 }
User.java
1 package org.fool.redis.model; 2 3 import java.util.Date; 4 import javax.persistence.*; 5 6 @Table(name = "tb_user") 7 public class User { 8 @Id 9 private Integer id; 10 11 /** 12 * 用户名 13 */ 14 private String username; 15 16 /** 17 * 密码 18 */ 19 private String password; 20 21 /** 22 * 性别 0=女 1=男 23 */ 24 private Byte sex; 25 26 /** 27 * 删除标志,默认0不删除,1删除 28 */ 29 @Column(name = "is_deleted") 30 private Boolean isDeleted; 31 32 /** 33 * 创建时间 34 */ 35 @Column(name = "create_time") 36 private Date createTime; 37 38 /** 39 * 更新时间 40 */ 41 @Column(name = "update_time") 42 private Date updateTime; 43 44 /** 45 * @return id 46 */ 47 public Integer getId() { 48 return id; 49 } 50 51 /** 52 * @param id 53 */ 54 public void setId(Integer id) { 55 this.id = id; 56 } 57 58 /** 59 * 获取用户名 60 * 61 * @return username - 用户名 62 */ 63 public String getUsername() { 64 return username; 65 } 66 67 /** 68 * 设置用户名 69 * 70 * @param username 用户名 71 */ 72 public void setUsername(String username) { 73 this.username = username == null ? null : username.trim(); 74 } 75 76 /** 77 * 获取密码 78 * 79 * @return password - 密码 80 */ 81 public String getPassword() { 82 return password; 83 } 84 85 /** 86 * 设置密码 87 * 88 * @param password 密码 89 */ 90 public void setPassword(String password) { 91 this.password = password == null ? null : password.trim(); 92 } 93 94 /** 95 * 获取性别 0=女 1=男 96 * 97 * @return sex - 性别 0=女 1=男 98 */ 99 public Byte getSex() { 100 return sex; 101 } 102 103 /** 104 * 设置性别 0=女 1=男 105 * 106 * @param sex 性别 0=女 1=男 107 */ 108 public void setSex(Byte sex) { 109 this.sex = sex; 110 } 111 112 /** 113 * 获取删除标志,默认0不删除,1删除 114 * 115 * @return is_deleted - 删除标志,默认0不删除,1删除 116 */ 117 public Boolean getIsDeleted() { 118 return isDeleted; 119 } 120 121 /** 122 * 设置删除标志,默认0不删除,1删除 123 * 124 * @param isDeleted 删除标志,默认0不删除,1删除 125 */ 126 public void setIsDeleted(Boolean isDeleted) { 127 this.isDeleted = isDeleted; 128 } 129 130 /** 131 * 获取创建时间 132 * 133 * @return create_time - 创建时间 134 */ 135 public Date getCreateTime() { 136 return createTime; 137 } 138 139 /** 140 * 设置创建时间 141 * 142 * @param createTime 创建时间 143 */ 144 public void setCreateTime(Date createTime) { 145 this.createTime = createTime; 146 } 147 148 /** 149 * 获取更新时间 150 * 151 * @return update_time - 更新时间 152 */ 153 public Date getUpdateTime() { 154 return updateTime; 155 } 156 157 /** 158 * 设置更新时间 159 * 160 * @param updateTime 更新时间 161 */ 162 public void setUpdateTime(Date updateTime) { 163 this.updateTime = updateTime; 164 } 165 166 @Override 167 public String toString() { 168 StringBuilder sb = new StringBuilder(); 169 sb.append(getClass().getSimpleName()); 170 sb.append(" ["); 171 sb.append("Hash = ").append(hashCode()); 172 sb.append(", id=").append(id); 173 sb.append(", username=").append(username); 174 sb.append(", password=").append(password); 175 sb.append(", sex=").append(sex); 176 sb.append(", isDeleted=").append(isDeleted); 177 sb.append(", createTime=").append(createTime); 178 sb.append(", updateTime=").append(updateTime); 179 sb.append("]"); 180 return sb.toString(); 181 } 182 }
UserMapper.java
1 package org.fool.redis.mapper; 2 3 import org.fool.redis.model.User; 4 import tk.mybatis.mapper.common.Mapper; 5 6 public interface UserMapper extends Mapper<User> { 7 }
Note: User.java 和 UserMapper.java 是通过插件 mybatis-generator-maven-plugin 执行命令 mybatis-generator:generate -e 生成
UserService.java
1 package org.fool.redis.service; 2 3 import lombok.extern.slf4j.Slf4j; 4 import org.fool.redis.mapper.UserMapper; 5 import org.fool.redis.model.User; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Service; 8 9 import java.util.List; 10 11 @Service 12 @Slf4j 13 public class UserService { 14 @Autowired 15 private UserMapper userMapper; 16 17 public void createUser(User user) { 18 userMapper.insertSelective(user); 19 } 20 21 public void updateUser(User user) { 22 userMapper.updateByPrimaryKeySelective(user); 23 } 24 25 public void findUser() { 26 log.info("select by primary key: where id = 100"); 27 User result = userMapper.selectByPrimaryKey(100); 28 log.info(result.toString()); 29 30 log.info("select by: where sex = 1"); 31 User user1 = new User(); 32 user1.setSex((byte) 1); 33 List<User> resultList = userMapper.select(user1); 34 log.info("sex=1 nums: {}", resultList.size()); 35 36 log.info("select by: where username = ? and password = ?"); 37 User user2 = new User(); 38 user2.setUsername("update100"); 39 user2.setPassword("update100"); 40 User user = userMapper.selectOne(user2); 41 log.info("user: {}", user); 42 } 43 44 public void deleteUser(int id) { 45 userMapper.deleteByPrimaryKey(id); 46 } 47 }
UserController.java
1 package org.fool.redis.controller; 2 3 import org.fool.redis.model.User; 4 import org.fool.redis.service.UserService; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.web.bind.annotation.DeleteMapping; 7 import org.springframework.web.bind.annotation.GetMapping; 8 import org.springframework.web.bind.annotation.PathVariable; 9 import org.springframework.web.bind.annotation.PostMapping; 10 import org.springframework.web.bind.annotation.PutMapping; 11 import org.springframework.web.bind.annotation.RestController; 12 13 import java.util.Random; 14 15 @RestController 16 public class UserController { 17 @Autowired 18 private UserService userService; 19 20 @PostMapping("/create") 21 public String create() { 22 for (int i = 0; i < 1000; i++) { 23 User user = new User(); 24 user.setUsername("user" + i); 25 user.setPassword("password" + i); 26 user.setSex((byte) new Random().nextInt(2)); 27 userService.createUser(user); 28 } 29 30 return "SUCCESS"; 31 } 32 33 @PutMapping("/update/{id}") 34 public String update(@PathVariable int id) { 35 User user = new User(); 36 user.setId(id); 37 String temp = "update" + id; 38 user.setUsername(temp); 39 user.setPassword(temp); 40 userService.updateUser(user); 41 42 return "SUCCESS"; 43 } 44 45 @GetMapping("/find") 46 public String find() { 47 userService.findUser(); 48 49 return "SUCCESS"; 50 } 51 52 @DeleteMapping("/delete/{id}") 53 public String delete(@PathVariable int id) { 54 userService.deleteUser(id); 55 56 return "SUCCESS"; 57 } 58 59 }
Test
create
curl --location --request POST 'http://localhost:8888/create' \ --header 'Content-Type: application/json' \ --data-raw ''
update
curl --location --request PUT 'http://localhost:8888/update/100' \ --header 'Content-Type: application/json' \ --data-raw ''
find
curl --location --request GET 'http://localhost:8888/find' \ --header 'Content-Type: application/json' \ --data-raw ''
delete
curl --location --request DELETE 'http://localhost:8888/delete/1' \ --header 'Content-Type: application/json' \ --data-raw ''
强者自救 圣者渡人