引入依赖

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>

application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
server:
port: 80
servlet:
context-path: /
tomcat:
uri-encoding: UTF-8

# 数据源配置
spring:
application:
name: microservice-student
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db_bookmanagesystem?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: 123456
jpa:
hibernate:
ddl-auto: update
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl #配置后可以通过@Column注解的name属性自定义数据库的字段名称
show-sql: true

实体类

使用了lombok,如果不想使用就自行生成setter和getter方法

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
package com.ledao.entity;

import lombok.Data;

import javax.persistence.*;

/**
* 用户实体类
*
* @author LeDao
* @company
* @create 2022-01-21 16:26
*/
@Data
@Entity
@Table(name = "t_user")
public class User {

/**
* 编号
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* 用户名
*/
@Column(name = "userName", length = 100)
private String userName;
/**
* 昵称
*/
@Column(name = "nickName", length = 100)
private String nickName;
/**
* 密码
*/
@Column(length = 100)
private String password;
/**
* 用户类型,1代表管理员,2代表普通用户
*/
private Integer type;
/**
* 用户状态,1代表正常,2代表被封禁
*/
private Integer state;
/**
* 是否可借书
*/
@Column(name = "isBorrow")
private Integer isBorrow;
}

Repository接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.ledao.repository;

import com.ledao.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

/**
* 用户Repository接口
*
* @author LeDao
* @company
* @create 2022-01-21 17:01
*/
public interface UserRepository extends JpaRepository<User, Long> {
}

测试

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
package com.ledao;

import com.ledao.entity.User;
import com.ledao.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@SpringBootTest
class BookManageSystemApplicationTests {

@Resource
private UserRepository userRepository;

@Test
void contextLoads() {
User user = new User();
user.setUserName("admin");
user.setNickName("乐道");
user.setPassword("admin");
user.setType(1);
user.setState(1);
user.setIsBorrow(1);
userRepository.save(user);
}

}

结果

如果数据库的t_user表中新增了一条记录,说明引入Spring Data JPA成功