You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. # spring-boot-demo-orm-mybatis-plus
  2. > 此 demo 演示了 Spring Boot 如何集成 mybatis-plus,简化Mybatis开发,带给你难以置信的开发体验。
  3. >
  4. > - 2019-09-14 新增:ActiveRecord 模式操作
  5. ## pom.xml
  6. ```xml
  7. <?xml version="1.0" encoding="UTF-8"?>
  8. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  9. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>spring-boot-demo-orm-mybatis-plus</artifactId>
  12. <version>1.0.0-SNAPSHOT</version>
  13. <packaging>jar</packaging>
  14. <name>spring-boot-demo-orm-mybatis-plus</name>
  15. <description>Demo project for Spring Boot</description>
  16. <parent>
  17. <groupId>com.xkcoding</groupId>
  18. <artifactId>spring-boot-demo</artifactId>
  19. <version>1.0.0-SNAPSHOT</version>
  20. </parent>
  21. <properties>
  22. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  23. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  24. <java.version>1.8</java.version>
  25. <mybatis.plus.version>3.0.5</mybatis.plus.version>
  26. </properties>
  27. <dependencies>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter</artifactId>
  31. </dependency>
  32. <dependency>
  33. <groupId>com.baomidou</groupId>
  34. <artifactId>mybatis-plus-boot-starter</artifactId>
  35. <version>${mybatis.plus.version}</version>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-starter-test</artifactId>
  40. <scope>test</scope>
  41. </dependency>
  42. <dependency>
  43. <groupId>mysql</groupId>
  44. <artifactId>mysql-connector-java</artifactId>
  45. </dependency>
  46. <dependency>
  47. <groupId>cn.hutool</groupId>
  48. <artifactId>hutool-all</artifactId>
  49. </dependency>
  50. <dependency>
  51. <groupId>com.google.guava</groupId>
  52. <artifactId>guava</artifactId>
  53. </dependency>
  54. <dependency>
  55. <groupId>org.projectlombok</groupId>
  56. <artifactId>lombok</artifactId>
  57. <optional>true</optional>
  58. </dependency>
  59. </dependencies>
  60. <build>
  61. <finalName>spring-boot-demo-orm-mybatis-plus</finalName>
  62. <plugins>
  63. <plugin>
  64. <groupId>org.springframework.boot</groupId>
  65. <artifactId>spring-boot-maven-plugin</artifactId>
  66. </plugin>
  67. </plugins>
  68. </build>
  69. </project>
  70. ```
  71. ## MybatisPlusConfig.java
  72. ```java
  73. /**
  74. * <p>
  75. * mybatis-plus 配置
  76. * </p>
  77. *
  78. * @author yangkai.shen
  79. * @date Created in 2018-11-08 17:29
  80. */
  81. @Configuration
  82. @MapperScan(basePackages = {"com.xkcoding.orm.mybatis.plus.mapper"})
  83. @EnableTransactionManagement
  84. public class MybatisPlusConfig {
  85. /**
  86. * 性能分析拦截器,不建议生产使用
  87. */
  88. @Bean
  89. public PerformanceInterceptor performanceInterceptor(){
  90. return new PerformanceInterceptor();
  91. }
  92. /**
  93. * 分页插件
  94. */
  95. @Bean
  96. public PaginationInterceptor paginationInterceptor() {
  97. return new PaginationInterceptor();
  98. }
  99. }
  100. ```
  101. ## CommonFieldHandler.java
  102. ```java
  103. package com.xkcoding.orm.mybatis.plus.config;
  104. import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
  105. import lombok.extern.slf4j.Slf4j;
  106. import org.apache.ibatis.reflection.MetaObject;
  107. import org.springframework.stereotype.Component;
  108. import java.util.Date;
  109. /**
  110. * <p>
  111. * 通用字段填充
  112. * </p>
  113. *
  114. * @author yangkai.shen
  115. * @date Created in 2018-11-08 17:40
  116. */
  117. @Slf4j
  118. @Component
  119. public class CommonFieldHandler implements MetaObjectHandler {
  120. @Override
  121. public void insertFill(MetaObject metaObject) {
  122. log.info("start insert fill ....");
  123. this.setFieldValByName("createTime", new Date(), metaObject);
  124. this.setFieldValByName("lastUpdateTime", new Date(), metaObject);
  125. }
  126. @Override
  127. public void updateFill(MetaObject metaObject) {
  128. log.info("start update fill ....");
  129. this.setFieldValByName("lastUpdateTime", new Date(), metaObject);
  130. }
  131. }
  132. ```
  133. ## application.yml
  134. ```yaml
  135. spring:
  136. datasource:
  137. url: jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
  138. username: root
  139. password: root
  140. driver-class-name: com.mysql.cj.jdbc.Driver
  141. type: com.zaxxer.hikari.HikariDataSource
  142. initialization-mode: always
  143. continue-on-error: true
  144. schema:
  145. - "classpath:db/schema.sql"
  146. data:
  147. - "classpath:db/data.sql"
  148. hikari:
  149. minimum-idle: 5
  150. connection-test-query: SELECT 1 FROM DUAL
  151. maximum-pool-size: 20
  152. auto-commit: true
  153. idle-timeout: 30000
  154. pool-name: SpringBootDemoHikariCP
  155. max-lifetime: 60000
  156. connection-timeout: 30000
  157. logging:
  158. level:
  159. com.xkcoding: debug
  160. com.xkcoding.orm.mybatis.plus.mapper: trace
  161. mybatis-plus:
  162. mapper-locations: classpath:mappers/*.xml
  163. #实体扫描,多个package用逗号或者分号分隔
  164. typeAliasesPackage: com.xkcoding.orm.mybatis.plus.entity
  165. global-config:
  166. # 数据库相关配置
  167. db-config:
  168. #主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID",ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
  169. id-type: auto
  170. #字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断"
  171. field-strategy: not_empty
  172. #驼峰下划线转换
  173. table-underline: true
  174. #是否开启大写命名,默认不开启
  175. #capital-mode: true
  176. #逻辑删除配置
  177. #logic-delete-value: 1
  178. #logic-not-delete-value: 0
  179. db-type: mysql
  180. #刷新mapper 调试神器
  181. refresh: true
  182. # 原生配置
  183. configuration:
  184. map-underscore-to-camel-case: true
  185. cache-enabled: true
  186. ```
  187. ## UserMapper.java
  188. ```java
  189. /**
  190. * <p>
  191. * UserMapper
  192. * </p>
  193. *
  194. * @author yangkai.shen
  195. * @date Created in 2018-11-08 16:57
  196. */
  197. @Component
  198. public interface UserMapper extends BaseMapper<User> {
  199. }
  200. ```
  201. ## UserService.java
  202. ```java
  203. /**
  204. * <p>
  205. * User Service
  206. * </p>
  207. *
  208. * @author yangkai.shen
  209. * @date Created in 2018-11-08 18:10
  210. */
  211. public interface UserService extends IService<User> {
  212. }
  213. ```
  214. ## UserServiceImpl.java
  215. ```java
  216. /**
  217. * <p>
  218. * User Service
  219. * </p>
  220. *
  221. * @author yangkai.shen
  222. * @date Created in 2018-11-08 18:10
  223. */
  224. @Service
  225. public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
  226. }
  227. ```
  228. ## UserServiceTest.java
  229. ```java
  230. /**
  231. * <p>
  232. * User Service 测试
  233. * </p>
  234. *
  235. * @author yangkai.shen
  236. * @date Created in 2018-11-08 18:13
  237. */
  238. @Slf4j
  239. public class UserServiceTest extends SpringBootDemoOrmMybatisPlusApplicationTests {
  240. @Autowired
  241. private UserService userService;
  242. /**
  243. * 测试Mybatis-Plus 新增
  244. */
  245. @Test
  246. public void testSave() {
  247. String salt = IdUtil.fastSimpleUUID();
  248. User testSave3 = User.builder().name("testSave3").password(SecureUtil.md5("123456" + salt)).salt(salt).email("testSave3@xkcoding.com").phoneNumber("17300000003").status(1).lastLoginTime(new DateTime()).build();
  249. boolean save = userService.save(testSave3);
  250. Assert.assertTrue(save);
  251. log.debug("【测试id回显#testSave3.getId()】= {}", testSave3.getId());
  252. }
  253. /**
  254. * 测试Mybatis-Plus 批量新增
  255. */
  256. @Test
  257. public void testSaveList() {
  258. List<User> userList = Lists.newArrayList();
  259. for (int i = 4; i < 14; i++) {
  260. String salt = IdUtil.fastSimpleUUID();
  261. User user = User.builder().name("testSave" + i).password(SecureUtil.md5("123456" + salt)).salt(salt).email("testSave" + i + "@xkcoding.com").phoneNumber("1730000000" + i).status(1).lastLoginTime(new DateTime()).build();
  262. userList.add(user);
  263. }
  264. boolean batch = userService.saveBatch(userList);
  265. Assert.assertTrue(batch);
  266. List<Long> ids = userList.stream().map(User::getId).collect(Collectors.toList());
  267. log.debug("【userList#ids】= {}", ids);
  268. }
  269. /**
  270. * 测试Mybatis-Plus 删除
  271. */
  272. @Test
  273. public void testDelete() {
  274. boolean remove = userService.removeById(1L);
  275. Assert.assertTrue(remove);
  276. User byId = userService.getById(1L);
  277. Assert.assertNull(byId);
  278. }
  279. /**
  280. * 测试Mybatis-Plus 修改
  281. */
  282. @Test
  283. public void testUpdate() {
  284. User user = userService.getById(1L);
  285. Assert.assertNotNull(user);
  286. user.setName("MybatisPlus修改名字");
  287. boolean b = userService.updateById(user);
  288. Assert.assertTrue(b);
  289. User update = userService.getById(1L);
  290. Assert.assertEquals("MybatisPlus修改名字", update.getName());
  291. log.debug("【update】= {}", update);
  292. }
  293. /**
  294. * 测试Mybatis-Plus 查询单个
  295. */
  296. @Test
  297. public void testQueryOne() {
  298. User user = userService.getById(1L);
  299. Assert.assertNotNull(user);
  300. log.debug("【user】= {}", user);
  301. }
  302. /**
  303. * 测试Mybatis-Plus 查询全部
  304. */
  305. @Test
  306. public void testQueryAll() {
  307. List<User> list = userService.list(new QueryWrapper<>());
  308. Assert.assertTrue(CollUtil.isNotEmpty(list));
  309. log.debug("【list】= {}", list);
  310. }
  311. /**
  312. * 测试Mybatis-Plus 分页排序查询
  313. */
  314. @Test
  315. public void testQueryByPageAndSort() {
  316. initData();
  317. int count = userService.count(new QueryWrapper<>());
  318. Page<User> userPage = new Page<>(1, 5);
  319. userPage.setDesc("id");
  320. IPage<User> page = userService.page(userPage, new QueryWrapper<>());
  321. Assert.assertEquals(5, page.getSize());
  322. Assert.assertEquals(count, page.getTotal());
  323. log.debug("【page.getRecords()】= {}", page.getRecords());
  324. }
  325. /**
  326. * 测试Mybatis-Plus 自定义查询
  327. */
  328. @Test
  329. public void testQueryByCondition() {
  330. initData();
  331. QueryWrapper<User> wrapper = new QueryWrapper<>();
  332. wrapper.like("name", "Save1").or().eq("phone_number", "17300000001").orderByDesc("id");
  333. int count = userService.count(wrapper);
  334. Page<User> userPage = new Page<>(1, 3);
  335. IPage<User> page = userService.page(userPage, wrapper);
  336. Assert.assertEquals(3, page.getSize());
  337. Assert.assertEquals(count, page.getTotal());
  338. log.debug("【page.getRecords()】= {}", page.getRecords());
  339. }
  340. /**
  341. * 初始化数据
  342. */
  343. private void initData() {
  344. testSaveList();
  345. }
  346. }
  347. ```
  348. ## 2019-09-14新增
  349. ### ActiveRecord 模式
  350. - Role.java
  351. ```java
  352. /**
  353. * <p>
  354. * 角色实体类
  355. * </p>
  356. *
  357. * @author yangkai.shen
  358. * @date Created in 2019-09-16 14:04
  359. */
  360. @Data
  361. @TableName("orm_role")
  362. @Accessors(chain = true)
  363. @EqualsAndHashCode(callSuper = true)
  364. public class Role extends Model<Role> {
  365. /**
  366. * 主键
  367. */
  368. private Long id;
  369. /**
  370. * 角色名
  371. */
  372. private String name;
  373. /**
  374. * 主键值,ActiveRecord 模式这个必须有,否则 xxById 的方法都将失效!
  375. * 即使使用 ActiveRecord 不会用到 RoleMapper,RoleMapper 这个接口也必须创建
  376. */
  377. @Override
  378. protected Serializable pkVal() {
  379. return this.id;
  380. }
  381. }
  382. ```
  383. - RoleMapper.java
  384. ```java
  385. /**
  386. * <p>
  387. * RoleMapper
  388. * </p>
  389. *
  390. * @author yangkai.shen
  391. * @date Created in 2019-09-16 14:06
  392. */
  393. public interface RoleMapper extends BaseMapper<Role> {
  394. }
  395. ```
  396. - ActiveRecordTest.java
  397. ```java
  398. /**
  399. * <p>
  400. * Role
  401. * </p>
  402. *
  403. * @author yangkai.shen
  404. * @date Created in 2019-09-16 14:19
  405. */
  406. @Slf4j
  407. public class ActiveRecordTest extends SpringBootDemoOrmMybatisPlusApplicationTests {
  408. /**
  409. * 测试 ActiveRecord 插入数据
  410. */
  411. @Test
  412. public void testActiveRecordInsert() {
  413. Role role = new Role();
  414. role.setName("VIP");
  415. Assert.assertTrue(role.insert());
  416. // 成功直接拿会写的 ID
  417. log.debug("【role】= {}", role);
  418. }
  419. /**
  420. * 测试 ActiveRecord 更新数据
  421. */
  422. @Test
  423. public void testActiveRecordUpdate() {
  424. Assert.assertTrue(new Role().setId(1L).setName("管理员-1").updateById());
  425. Assert.assertTrue(new Role().update(new UpdateWrapper<Role>().lambda().set(Role::getName, "普通用户-1").eq(Role::getId, 2)));
  426. }
  427. /**
  428. * 测试 ActiveRecord 查询数据
  429. */
  430. @Test
  431. public void testActiveRecordSelect() {
  432. Assert.assertEquals("管理员", new Role().setId(1L).selectById().getName());
  433. Role role = new Role().selectOne(new QueryWrapper<Role>().lambda().eq(Role::getId, 2));
  434. Assert.assertEquals("普通用户", role.getName());
  435. List<Role> roles = new Role().selectAll();
  436. Assert.assertTrue(roles.size() > 0);
  437. log.debug("【roles】= {}", roles);
  438. }
  439. /**
  440. * 测试 ActiveRecord 删除数据
  441. */
  442. @Test
  443. public void testActiveRecordDelete() {
  444. Assert.assertTrue(new Role().setId(1L).deleteById());
  445. Assert.assertTrue(new Role().delete(new QueryWrapper<Role>().lambda().eq(Role::getName, "普通用户")));
  446. }
  447. }
  448. ```
  449. ## 参考
  450. - mybatis-plus官方文档:http://mp.baomidou.com/