项目搭建[2]springboot的mysql的配置及JPA的使用

mysql的配置

首先在maven中引入依赖:

1
2
3
4
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

然后在配置文件中配置:

1
2
3
4
5
6
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://127.0.0.1/database_name?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC

JPA的使用

基础配置使用

首先在maven中引入依赖:

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

然后在配置文件中设置(打印sql):

1
2
jpa:
show-sql: true

新建entity包并创建文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Data
@ToString
@Entity
@DynamicUpdate
public class ProductCategory {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer categoryId;

private String categoryName;

private Integer categoryType;
}

如果类名和表名的关系不是驼峰转下划线的关系的话,我们可以使用@Table注解来配置表名:

1
2
3
4
@Table(name = "t_product_category")
public class ProductCategory {
...
}

新建repository包并创建Repository接口:

1
2
3
4
public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Integer> {

List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
}

DynamicUpdate注解说明

在实际业务场景中,我们经常会从数据库中查出一条数据,对其做一些修改后再更新数据库,如果我们更新时将原来的update_time传入,就会使数据库默认的update_time失效。
这时我们可以为entity类加上DynamicUpdate注解自动更新数据库时间。

1
2
3
4
5
@Entity
@DynamicUpdate
public class ProductCategory {
...
}

测试方法

我们可以写一个测试类来测试表的增删改查:

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
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductCategoryTest {

@Autowired
private ProductCategoryRepository repository;

@Test
public void findOneTest() {
ProductCategory one = repository.findById(1).orElse(null);
Assert.assertNotNull(one);
}

@Test
public void saveTest() {
ProductCategory productCategory = new ProductCategory();
productCategory.setCategoryName("女生最爱");
productCategory.setCategoryType(3);
repository.save(productCategory);
}

@Test
public void updateTest() {
ProductCategory productCategory = new ProductCategory();
productCategory.setCategoryId(2);
productCategory.setCategoryName("男生最爱");
productCategory.setCategoryType(3);
repository.save(productCategory);
}

@Test
public void findByCategoryTypeInList() {
List<Integer> list = Arrays.asList(2, 3, 4);
List<ProductCategory> productCategories = repository.findByCategoryTypeIn(list);
Assert.assertNotEquals(productCategories.size(), 0);
}
}

常见错误

如果编辑器报错:

1
Inferred type 'S' for type parameter 'S' is not within its bound;

这是由于使用SpringBoot是2版本但直接调用了find方法如下:

1
ProductCategory one = repository.findById(1);

这在SpringBoot 2.X中已经不允许了。

  1. 将版本换回1.5.4。

  2. 写成以下形式:

1
ProductCategory one = repository.findById(1).orElse(null);

如果编辑器报错:

1
Table 'sell.hibernate_sequence' doesn't exist

如果我们使用以下写法就会报错,这也是因为SpringBoot2.X使用了hibernate5导致的。

1
@GeneratedValue
  1. 版本切换

  2. 写成如下形式:

1
@GeneratedValue(strategy = GenerationType.IDENTITY)