mysql的配置
首先在maven中引入依赖:1
2
3
4
mysql
mysql-connector-java
然后在配置文档中配置:1
2
3
4
5
6spring:
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
JPA的使用
基础配置使用
首先在maven中引入依赖:1
2
3
4
org.springframework.boot
spring-boot-starter-data-jpa
然后在配置文档中设置(打印sql):1
2jpa:
show-sql: true
新建entity包并创建文档:1
2
3
4
5
6
7
8
9
10
11
12
13
14@Entity
@DynamicUpdate
public class{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer categoryId;
private String categoryName;
private Integer categoryType;
}
如果类名和表名的关系不是驼峰转下划线的关系的话,[email protected]:1
2
3
4@Table(name = "t_product_category")
public class{
...
}
新建repository包并创建Repository接口:1
2
3
4public interface ProductCategoryRepository extends JpaRepository{
List findByCategoryTypeIn(List 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 list = Arrays.asList(2, 3, 4);
List productCategories = repository.findByCategoryTypeIn(list);
Assert.assertNotEquals(productCategories.size(), 0);
}
}
常见错误
如果编辑器报错:1Inferred type 'S' for type parameter 'S' is not within its bound;
这是由于使用SpringBoot是2版本但直接调用了find方法如下:1ProductCategory one = repository.findById(1);
这在SpringBoot 2.X中已经不允许了。将版本换回1.5.4。
写成以下形式:1ProductCategory one = repository.findById(1).orElse(null);
如果编辑器报错:1Table 'sell.hibernate_sequence' doesn't exist
如果我们使用以下写法就会报错,这也是因为SpringBoot2.X使用了hibernate5导致的。1@GeneratedValue版本切换
写成如下形式:1@GeneratedValue(strategy = GenerationType.IDENTITY)