Spring Boot JPA

1.创建子模块

这里我们创建一个子模块

1
2
group = 'com.ray.study'
artifact ='spring-boot-05-jpa'

2.引入依赖

2.1 继承父工程依赖

在父工程spring-boot-seedssettings.gradle加入子工程

1
2
3
4
5
6
rootProject.name = 'spring-boot-seeds'
include 'spring-boot-01-helloworld'
include 'spring-boot-02-restful-test'
include 'spring-boot-03-thymeleaf'
include 'spring-boot-04-swagger2'
include 'spring-boot-05-jpa'

这样,子工程spring-boot-05-jpa就会自动继承父工程中subprojects `函数里声明的依赖,主要包含如下依赖:

1
2
3
4
5
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'

2.2 引入jpa依赖

将子模块spring-boot-05-jpabuild.gradle修改为如下内容:

1
2
3
4
5
6
7
dependencies {
// jpa
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

// mysql 驱动
implementation 'mysql:mysql-connector-java'
}

3.修改配置

3.1 修改application.yml

主要配置下数据源与JPA

由于我们配置的ddl-auto = update,因此不需要创建相关数据表,只需要创建integrate-jpa数据库即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server:
port: 8088
servlet:
context-path: /

spring:
datasource: # 配置数据源
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/integrate-jpa?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: root
jpa: # 配置jpa
database: mysql # 数据库类型
show-sql: true # 打印sql语句
hibernate:
ddl-auto: update # 加载 Hibernate时, 自动更新数据库结构

数据源的配置类为DataSourceProperties,具体的默认配置:

1
2
3
4
5
6
// 默认配置见 determineDriverClassName 、 determineUsername、determineUrl、determinePassword
public DataSourceBuilder<?> initializeDataSourceBuilder() {
return DataSourceBuilder.create(getClassLoader()).type(getType())
.driverClassName(determineDriverClassName()).url(determineUrl())
.username(determineUsername()).password(determinePassword());
}

JPA的配置类为JpaPropertiesHibernateProperties

Hibernate DDL配置的含义:

  • create: 每次运行程序时,都会重新创建表,故而数据会丢失
  • create-drop: 每次运行程序时会先创建表结构,然后待程序结束时清空表
  • upadte: 每次运行程序,没有表时会创建表,如果对象发生改变会更新表结构,原有数据不会清空,只会更新(推荐使用)
  • validate: 运行程序会校验数据与数据库的字段类型是否相同,字段不同会报错

4.业务实现

4.1 model

(1)BaseDO

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.ray.study.springboot05jpa.model;


import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.util.Date;

/**
* BaseDO
*
*/
@Data
@NoArgsConstructor
@MappedSuperclass // 声明子类可继承基类字段
public class BaseDO {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@JsonIgnore
private Date creationDate;

@JsonIgnore
private Date lastUpdateDate;
}


(2)User

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.ray.study.springboot05jpa.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.Table;


/**
* 用户模型
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "user")
public class User extends BaseDO{

/**
* 用户名
*/
private String name;

/**
* 年龄
*/
private Integer age;


}


4.2 repository

  • UserRepository
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.ray.study.springboot05jpa.repository;

import com.ray.study.springboot05jpa.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
* description
*
*/
@Repository
public interface UserRepository extends JpaRepository<User, Long> {

/**
* 查询年龄大于等于指定年龄的用户
* @param age 年龄
* @return userList
*/
List<User> findByAgeGreaterThanEqualOrderById(Integer age);

/**
* 根据用户名查询用户信息
*
* @param name 用户名
* @return userList
*/
List<User> findAllByName(String name);


/**
* 根据用户名模糊查询
* @param name username
* @return userList
*/
List<User> findByNameLike(String name);

/**
* 模糊查询
* @param name
* @return
*/
List<User> findByNameContaining(String name);
}

5.单元测试

  • UserRepositoryTest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package com.ray.study.springboot05jpa.repository;

import com.ray.study.springboot05jpa.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

/**
* description
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepositoryTest {

@Autowired
UserRepository userRepository;


/**
* 查询用户
*/
@Test
public void queryUser(){
List<User> userToAddList = new ArrayList<>();
userToAddList.add(new User("aatomcat000",20));
userToAddList.add(new User("tomcat",21));
userToAddList.add(new User("tttomcat",22));
userToAddList.add(new User("tttomcat111",23));
userToAddList.add(new User("tomcataaa",24));

// 新增用户
userToAddList.forEach(user -> {
userRepository.save(user);
});




// 查询所有名字为tom的用户
List<User> userList = userRepository.findAllByName("tom");
// assertThat(userList.size(), is(1));
System.out.println(userList);

// 查询所有年龄大于等于 21 的用户
List<User> userList2 = userRepository.findByAgeGreaterThanEqualOrderById(21);
//assertThat(userList2.size(), is(notNullValue()));
System.out.println(userList2);

// 精确查询,这里的like 并不是模糊查询
List<User> userList3 = userRepository.findByNameLike("tom");
//assertThat(userList3.size(), is(notNullValue()));
System.out.println(userList3);

// 模糊查询: Containing才是模糊查询
List<User> userList4 = userRepository.findByNameContaining("tom");
//assertThat(userList4.size(), is(notNullValue()));
System.out.println(userList4);
}


/**
* 新增用户
*/
@Test
public void insertUser(){

User user = new User();
user.setName("tom");
user.setAge(21);
User user1 = userRepository.save(user);

assertThat(user.getId(),is(notNullValue()));
}


/**
* 更新用户
*/
@Test
public void updateUser(){

User user = new User();
user.setId(1L);
user.setName("tom2");
user.setAge(1212);
User user1 = userRepository.save(user);

Optional<User> optionalUser = userRepository.findById(1L);
User updatedUser = null;
if(optionalUser.isPresent()){
updatedUser = optionalUser.get();
}

assertThat(updatedUser.getAge(),is(1212));
}


/**
* 删除用户
*/
@Test
public void deleteUser(){
User user = new User();
user.setName("tom2");
userRepository.delete(user);

List<User> userList = userRepository.findAllByName("tom2");
assertThat(userList, is(nullValue()));

}

}