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 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. # spring-boot-demo-orm-jpa
  2. > 此 demo 主要演示了 Spring Boot 如何使用 JPA 操作数据库,包含简单使用以及级联使用。
  3. ## 主要代码
  4. ### pom.xml
  5. ```xml
  6. <?xml version="1.0" encoding="UTF-8"?>
  7. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  8. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  9. <modelVersion>4.0.0</modelVersion>
  10. <artifactId>spring-boot-demo-orm-jpa</artifactId>
  11. <version>1.0.0-SNAPSHOT</version>
  12. <packaging>jar</packaging>
  13. <name>spring-boot-demo-orm-jpa</name>
  14. <description>Demo project for Spring Boot</description>
  15. <parent>
  16. <groupId>com.xkcoding</groupId>
  17. <artifactId>spring-boot-demo</artifactId>
  18. <version>1.0.0-SNAPSHOT</version>
  19. </parent>
  20. <properties>
  21. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  22. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  23. <java.version>1.8</java.version>
  24. </properties>
  25. <dependencies>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-data-jpa</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter</artifactId>
  33. </dependency>
  34. <dependency>
  35. <groupId>mysql</groupId>
  36. <artifactId>mysql-connector-java</artifactId>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-test</artifactId>
  41. <scope>test</scope>
  42. </dependency>
  43. <dependency>
  44. <groupId>cn.hutool</groupId>
  45. <artifactId>hutool-all</artifactId>
  46. </dependency>
  47. <dependency>
  48. <groupId>com.google.guava</groupId>
  49. <artifactId>guava</artifactId>
  50. </dependency>
  51. <dependency>
  52. <groupId>org.projectlombok</groupId>
  53. <artifactId>lombok</artifactId>
  54. <optional>true</optional>
  55. </dependency>
  56. </dependencies>
  57. <build>
  58. <finalName>spring-boot-demo-orm-jpa</finalName>
  59. <plugins>
  60. <plugin>
  61. <groupId>org.springframework.boot</groupId>
  62. <artifactId>spring-boot-maven-plugin</artifactId>
  63. </plugin>
  64. </plugins>
  65. </build>
  66. </project>
  67. ```
  68. ### JpaConfig.java
  69. ```java
  70. /**
  71. * <p>
  72. * JPA配置类
  73. * </p>
  74. *
  75. * @author yangkai.shen
  76. * @date Created in 2018-11-07 11:05
  77. */
  78. @Configuration
  79. @EnableTransactionManagement
  80. @EnableJpaAuditing
  81. @EnableJpaRepositories(basePackages = "com.xkcoding.orm.jpa.repository", transactionManagerRef = "jpaTransactionManager")
  82. public class JpaConfig {
  83. @Bean
  84. @ConfigurationProperties(prefix = "spring.datasource")
  85. public DataSource dataSource() {
  86. return DataSourceBuilder.create().build();
  87. }
  88. @Bean
  89. public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
  90. HibernateJpaVendorAdapter japVendor = new HibernateJpaVendorAdapter();
  91. japVendor.setGenerateDdl(false);
  92. LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
  93. entityManagerFactory.setDataSource(dataSource());
  94. entityManagerFactory.setJpaVendorAdapter(japVendor);
  95. entityManagerFactory.setPackagesToScan("com.xkcoding.orm.jpa.entity");
  96. return entityManagerFactory;
  97. }
  98. @Bean
  99. public PlatformTransactionManager jpaTransactionManager(EntityManagerFactory entityManagerFactory) {
  100. JpaTransactionManager transactionManager = new JpaTransactionManager();
  101. transactionManager.setEntityManagerFactory(entityManagerFactory);
  102. return transactionManager;
  103. }
  104. }
  105. ```
  106. ### User.java
  107. ```java
  108. /**
  109. * <p>
  110. * 用户实体类
  111. * </p>
  112. *
  113. * @author yangkai.shen
  114. * @date Created in 2018-11-07 14:06
  115. */
  116. @EqualsAndHashCode(callSuper = true)
  117. @NoArgsConstructor
  118. @AllArgsConstructor
  119. @Data
  120. @Builder
  121. @Entity
  122. @Table(name = "orm_user")
  123. @ToString(callSuper = true)
  124. public class User extends AbstractAuditModel {
  125. /**
  126. * 用户名
  127. */
  128. private String name;
  129. /**
  130. * 加密后的密码
  131. */
  132. private String password;
  133. /**
  134. * 加密使用的盐
  135. */
  136. private String salt;
  137. /**
  138. * 邮箱
  139. */
  140. private String email;
  141. /**
  142. * 手机号码
  143. */
  144. @Column(name = "phone_number")
  145. private String phoneNumber;
  146. /**
  147. * 状态,-1:逻辑删除,0:禁用,1:启用
  148. */
  149. private Integer status;
  150. /**
  151. * 上次登录时间
  152. */
  153. @Column(name = "last_login_time")
  154. private Date lastLoginTime;
  155. /**
  156. * 关联部门表
  157. * 1、关系维护端,负责多对多关系的绑定和解除
  158. * 2、@JoinTable注解的name属性指定关联表的名字,joinColumns指定外键的名字,关联到关系维护端(User)
  159. * 3、inverseJoinColumns指定外键的名字,要关联的关系被维护端(Department)
  160. * 4、其实可以不使用@JoinTable注解,默认生成的关联表名称为主表表名+下划线+从表表名,
  161. * 即表名为user_department
  162. * 关联到主表的外键名:主表名+下划线+主表中的主键列名,即user_id,这里使用referencedColumnName指定
  163. * 关联到从表的外键名:主表中用于关联的属性名+下划线+从表的主键列名,department_id
  164. * 主表就是关系维护端对应的表,从表就是关系被维护端对应的表
  165. */
  166. @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  167. @JoinTable(name = "orm_user_dept", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "dept_id", referencedColumnName = "id"))
  168. private Collection<Department> departmentList;
  169. }
  170. ```
  171. ### Department.java
  172. ```java
  173. /**
  174. * <p>
  175. * 部门实体类
  176. * </p>
  177. *
  178. * @author 76peter
  179. * @date Created in 2019-10-01 18:07
  180. */
  181. @EqualsAndHashCode(callSuper = true)
  182. @Data
  183. @NoArgsConstructor
  184. @AllArgsConstructor
  185. @Builder
  186. @Entity
  187. @Table(name = "orm_department")
  188. @ToString(callSuper = true)
  189. public class Department extends AbstractAuditModel {
  190. /**
  191. * 部门名
  192. */
  193. @Column(name = "name", columnDefinition = "varchar(255) not null")
  194. private String name;
  195. /**
  196. * 上级部门id
  197. */
  198. @ManyToOne(cascade = {CascadeType.REFRESH}, optional = true)
  199. @JoinColumn(name = "superior", referencedColumnName = "id")
  200. private Department superior;
  201. /**
  202. * 所属层级
  203. */
  204. @Column(name = "levels", columnDefinition = "int not null default 0")
  205. private Integer levels;
  206. /**
  207. * 排序
  208. */
  209. @Column(name = "order_no", columnDefinition = "int not null default 0")
  210. private Integer orderNo;
  211. /**
  212. * 子部门集合
  213. */
  214. @OneToMany(cascade = {CascadeType.REFRESH, CascadeType.REMOVE}, fetch = FetchType.EAGER, mappedBy = "superior")
  215. private Collection<Department> children;
  216. /**
  217. * 部门下用户集合
  218. */
  219. @ManyToMany(mappedBy = "departmentList")
  220. private Collection<User> userList;
  221. }
  222. ```
  223. ### AbstractAuditModel.java
  224. ```java
  225. /**
  226. * <p>
  227. * 实体通用父类
  228. * </p>
  229. *
  230. * @author yangkai.shen
  231. * @date Created in 2018-11-07 14:01
  232. */
  233. @MappedSuperclass
  234. @EntityListeners(AuditingEntityListener.class)
  235. @Data
  236. public abstract class AbstractAuditModel implements Serializable {
  237. /**
  238. * 主键
  239. */
  240. @Id
  241. @GeneratedValue(strategy = GenerationType.IDENTITY)
  242. private Long id;
  243. /**
  244. * 创建时间
  245. */
  246. @Temporal(TemporalType.TIMESTAMP)
  247. @Column(name = "create_time", nullable = false, updatable = false)
  248. @CreatedDate
  249. private Date createTime;
  250. /**
  251. * 上次更新时间
  252. */
  253. @Temporal(TemporalType.TIMESTAMP)
  254. @Column(name = "last_update_time", nullable = false)
  255. @LastModifiedDate
  256. private Date lastUpdateTime;
  257. }
  258. ```
  259. ### UserDao.java
  260. ```java
  261. /**
  262. * <p>
  263. * User Dao
  264. * </p>
  265. *
  266. * @author yangkai.shen
  267. * @date Created in 2018-11-07 14:07
  268. */
  269. @Repository
  270. public interface UserDao extends JpaRepository<User, Long> {
  271. }
  272. ```
  273. ### DepartmentDao.java
  274. ```java
  275. /**
  276. * <p>
  277. * User Dao
  278. * </p>
  279. *
  280. * @author 76peter
  281. * @date Created in 2019-10-01 18:07
  282. */
  283. @Repository
  284. public interface DepartmentDao extends JpaRepository<Department, Long> {
  285. /**
  286. * 根据层级查询部门
  287. *
  288. * @param level 层级
  289. * @return 部门列表
  290. */
  291. List<Department> findDepartmentsByLevels(Integer level);
  292. }
  293. ```
  294. ### application.yml
  295. ```yaml
  296. server:
  297. port: 8080
  298. servlet:
  299. context-path: /demo
  300. spring:
  301. datasource:
  302. jdbc-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
  303. username: root
  304. password: root
  305. driver-class-name: com.mysql.cj.jdbc.Driver
  306. type: com.zaxxer.hikari.HikariDataSource
  307. initialization-mode: always
  308. continue-on-error: true
  309. schema:
  310. - "classpath:db/schema.sql"
  311. data:
  312. - "classpath:db/data.sql"
  313. hikari:
  314. minimum-idle: 5
  315. connection-test-query: SELECT 1 FROM DUAL
  316. maximum-pool-size: 20
  317. auto-commit: true
  318. idle-timeout: 30000
  319. pool-name: SpringBootDemoHikariCP
  320. max-lifetime: 60000
  321. connection-timeout: 30000
  322. jpa:
  323. show-sql: true
  324. hibernate:
  325. ddl-auto: validate
  326. properties:
  327. hibernate:
  328. dialect: org.hibernate.dialect.MySQL57InnoDBDialect
  329. open-in-view: true
  330. logging:
  331. level:
  332. com.xkcoding: debug
  333. org.hibernate.SQL: debug
  334. org.hibernate.type: trace
  335. ```
  336. ### UserDaoTest.java
  337. ```java
  338. /**
  339. * <p>
  340. * jpa 测试类
  341. * </p>
  342. *
  343. * @author yangkai.shen
  344. * @date Created in 2018-11-07 14:09
  345. */
  346. @Slf4j
  347. public class UserDaoTest extends SpringBootDemoOrmJpaApplicationTests {
  348. @Autowired
  349. private UserDao userDao;
  350. /**
  351. * 测试保存
  352. */
  353. @Test
  354. public void testSave() {
  355. String salt = IdUtil.fastSimpleUUID();
  356. 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();
  357. userDao.save(testSave3);
  358. Assert.assertNotNull(testSave3.getId());
  359. Optional<User> byId = userDao.findById(testSave3.getId());
  360. Assert.assertTrue(byId.isPresent());
  361. log.debug("【byId】= {}", byId.get());
  362. }
  363. /**
  364. * 测试删除
  365. */
  366. @Test
  367. public void testDelete() {
  368. long count = userDao.count();
  369. userDao.deleteById(1L);
  370. long left = userDao.count();
  371. Assert.assertEquals(count - 1, left);
  372. }
  373. /**
  374. * 测试修改
  375. */
  376. @Test
  377. public void testUpdate() {
  378. userDao.findById(1L).ifPresent(user -> {
  379. user.setName("JPA修改名字");
  380. userDao.save(user);
  381. });
  382. Assert.assertEquals("JPA修改名字", userDao.findById(1L).get().getName());
  383. }
  384. /**
  385. * 测试查询单个
  386. */
  387. @Test
  388. public void testQueryOne() {
  389. Optional<User> byId = userDao.findById(1L);
  390. Assert.assertTrue(byId.isPresent());
  391. log.debug("【byId】= {}", byId.get());
  392. }
  393. /**
  394. * 测试查询所有
  395. */
  396. @Test
  397. public void testQueryAll() {
  398. List<User> users = userDao.findAll();
  399. Assert.assertNotEquals(0, users.size());
  400. log.debug("【users】= {}", users);
  401. }
  402. /**
  403. * 测试分页排序查询
  404. */
  405. @Test
  406. public void testQueryPage() {
  407. // 初始化数据
  408. initData();
  409. // JPA分页的时候起始页是页码减1
  410. Integer currentPage = 0;
  411. Integer pageSize = 5;
  412. Sort sort = Sort.by(Sort.Direction.DESC, "id");
  413. PageRequest pageRequest = PageRequest.of(currentPage, pageSize, sort);
  414. Page<User> userPage = userDao.findAll(pageRequest);
  415. Assert.assertEquals(5, userPage.getSize());
  416. Assert.assertEquals(userDao.count(), userPage.getTotalElements());
  417. log.debug("【id】= {}", userPage.getContent().stream().map(User::getId).collect(Collectors.toList()));
  418. }
  419. /**
  420. * 初始化10条数据
  421. */
  422. private void initData() {
  423. List<User> userList = Lists.newArrayList();
  424. for (int i = 0; i < 10; i++) {
  425. String salt = IdUtil.fastSimpleUUID();
  426. int index = 3 + i;
  427. User user = User.builder().name("testSave" + index).password(SecureUtil.md5("123456" + salt)).salt(salt).email("testSave" + index + "@xkcoding.com").phoneNumber("1730000000" + index).status(1).lastLoginTime(new DateTime()).build();
  428. userList.add(user);
  429. }
  430. userDao.saveAll(userList);
  431. }
  432. }
  433. ```
  434. ### DepartmentDaoTest.java
  435. ```java
  436. /**
  437. * <p>
  438. * jpa 测试类
  439. * </p>
  440. *
  441. * @author 76peter
  442. * @date Created in 2018-11-07 14:09
  443. */
  444. @Slf4j
  445. public class DepartmentDaoTest extends SpringBootDemoOrmJpaApplicationTests {
  446. @Autowired
  447. private DepartmentDao departmentDao;
  448. @Autowired
  449. private UserDao userDao;
  450. /**
  451. * 测试保存 ,根节点
  452. */
  453. @Test
  454. @Transactional
  455. public void testSave() {
  456. Collection<Department> departmentList = departmentDao.findDepartmentsByLevels(0);
  457. if (departmentList.size() == 0) {
  458. Department testSave1 = Department.builder().name("testSave1").orderNo(0).levels(0).superior(null).build();
  459. Department testSave1_1 = Department.builder().name("testSave1_1").orderNo(0).levels(1).superior(testSave1).build();
  460. Department testSave1_2 = Department.builder().name("testSave1_2").orderNo(0).levels(1).superior(testSave1).build();
  461. Department testSave1_1_1 = Department.builder().name("testSave1_1_1").orderNo(0).levels(2).superior(testSave1_1).build();
  462. departmentList.add(testSave1);
  463. departmentList.add(testSave1_1);
  464. departmentList.add(testSave1_2);
  465. departmentList.add(testSave1_1_1);
  466. departmentDao.saveAll(departmentList);
  467. Collection<Department> deptall = departmentDao.findAll();
  468. log.debug("【部门】= {}", JSONArray.toJSONString((List) deptall));
  469. }
  470. userDao.findById(1L).ifPresent(user -> {
  471. user.setName("添加部门");
  472. Department dept = departmentDao.findById(2L).get();
  473. user.setDepartmentList(departmentList);
  474. userDao.save(user);
  475. });
  476. log.debug("用户部门={}", JSONUtil.toJsonStr(userDao.findById(1L).get().getDepartmentList()));
  477. departmentDao.findById(2L).ifPresent(dept -> {
  478. Collection<User> userlist = dept.getUserList();
  479. //关联关系由user维护中间表,department userlist不会发生变化,可以增加查询方法来处理 重写getUserList方法
  480. log.debug("部门下用户={}", JSONUtil.toJsonStr(userlist));
  481. });
  482. userDao.findById(1L).ifPresent(user -> {
  483. user.setName("清空部门");
  484. user.setDepartmentList(null);
  485. userDao.save(user);
  486. });
  487. log.debug("用户部门={}", userDao.findById(1L).get().getDepartmentList());
  488. }
  489. }
  490. ```
  491. ### 其余代码及 SQL 参见本 demo
  492. ## 参考
  493. - Spring Data JPA 官方文档:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/