本篇要点
The Java Persistence API is a standard technology that lets you “map” objects to relational databases. The spring-boot-starter-data-jpa POM provides a quick way to get started.
The Java Persistence API
标准,Java持久层API,是一种能让对象能够快速映射到关系型数据库的技术规范。Hibernate
是最为强大的一个。Spring Data JPA
是采用基于JPA规范的Hibernate
框架基础下提供了Repository
层的实现。Spring Data Repository
极大地简化了实现各种持久层的数据库访问而写的样板代码量,同时CrudRepository
提供了丰富的CRUD功能去管理实体类。SpringBoot框架为Spring Data JPA提供了整合,spring-boot-starter-data-jpa
能够让你快速使用这门技术,它提供了以下依赖。
<!--SpringBoot对jpa的封装-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--mysql驱动,8.x版本-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/jpa?serverTimezone=GMT%2B8
username: root
password: 123456
hikari:
maximum-pool-size: 20
minimum-idle: 5
jpa:
#在建表的时候,将默认的存储引擎切换为 InnoDB
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
# 配置在日志中打印出执行的 SQL 语句信息。
show-sql: true
# 配置指明在程序启动的时候要删除并且创建实体类对应的表。
hibernate:
ddl-auto: create #update
值得注意的是:spring.jpa.hibernate.ddl-auto
第一建表的时候可以create,指明在程序启动的时候要删除并且创建实体类对应的表。后续使用就需要改为update。
JPA规范定义在javax.persistence
包下,注意导包的时候不要导错。
@Entity(name = "t_user")
@Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
@Transient
private String email;
}
t_user
。首先在数据库中创建jpa库,库名无所谓,和配置对应上就可以。
启动项目,你会发现控制台输出日志如下:
Hibernate: drop table if exists t_user
Hibernate: create table t_user
(id bigint not null auto_increment, password varchar(255), username varchar(255), primary key (id)) engine=InnoDB
此时我们配置的create效果已经显现,我们之后将它改为update,不然每次启动程序,数据表又得重建咯。
Working with Spring Data Repositories
Spring Data JPA repositories是你可以定义访问数据的接口,JPA查询是根据你的方法名称自动创建的。
这里我们编写一个接口,继承JpaRepository即可。User是对象名,不是表名,Long为主键的类型。
public interface UserDao extends JpaRepository<User, Long> {
/**
* 根据用户名和密码查询用户
*/
User findByUsernameAndPassword(String username, String password);
}
JPA默认支持常见的增删改查,也支持findByUsernameAndPassword
这种以字段命名的方法,对于更复杂的查询,您可以使用Spring Data的Query注解对方法进行注解。
Keyword | Sample | JPQL snippet |
---|---|---|
Distinct | findDistinctByLastnameAndFirstname | select distinct … where x.lastname = ?1 and x.firstname = ?2 |
And | findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | … where x.lastname = ?1 or x.firstname = ?2 |
Is, Equals | findByFirstname,findByFirstnameIs,findByFirstnameEquals | … where x.firstname = ?1 |
Between | findByStartDateBetween | … where x.startDate between ?1 and ?2 |
LessThan | findByAgeLessThan | … where x.age < ?1 |
LessThanEqual | findByAgeLessThanEqual | … where x.age <= ?1 |
GreaterThan | findByAgeGreaterThan | … where x.age > ?1 |
GreaterThanEqual | findByAgeGreaterThanEqual | … where x.age >= ?1 |
After | findByStartDateAfter | … where x.startDate > ?1 |
Before | findByStartDateBefore | … where x.startDate < ?1 |
IsNull, Null | findByAge(Is)Null | … where x.age is null |
IsNotNull, NotNull | findByAge(Is)NotNull | … where x.age not null |
Like | findByFirstnameLike | … where x.firstname like ?1 |
NotLike | findByFirstnameNotLike | … where x.firstname not like ?1 |
StartingWith | findByFirstnameStartingWith | … where x.firstname like ?1 (parameter bound with appended %) |
EndingWith | findByFirstnameEndingWith | … where x.firstname like ?1 (parameter bound with prepended %) |
Containing | findByFirstnameContaining | … where x.firstname like ?1 (parameter bound wrapped in %) |
OrderBy | findByAgeOrderByLastnameDesc | … where x.age = ?1 order by x.lastname desc |
Not | findByLastnameNot | … where x.lastname <> ?1 |
In | findByAgeIn(Collection ages) | … where x.age in ?1 |
NotIn | findByAgeNotIn(Collection ages) | … where x.age not in ?1 |
True | findByActiveTrue() | … where x.active = true |
False | findByActiveFalse() | … where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(x.firstname) = UPPER(?1) |
@SpringBootTest
class SpringBootJpaApplicationTests {
@Resource
UserDao userDao;
@Test
void testJPA() {
User user = userDao.save(new User(null, "summerday", "123456", "hangzhou"));
System.out.println("添加用户: " + user);
User u = userDao.findByUsernameAndPassword("summerday", "123456");
System.out.println("根据用户名和密码查询用户: " + u);
long count = userDao.count();
System.out.println("当前用户数量: " + count);
PageRequest page = PageRequest.of(0, 5, Sort.by(Sort.Order.desc("id")));
Page<User> all = userDao.findAll(page);
System.out.println("分页 + 根据id逆序 查询结果: " + all.getContent());
if(userDao.existsById(u.getId())) {
userDao.deleteById(u.getId());
System.out.println("删除id为" + u.getId()+ "的用户成功");
}
long c = userDao.count();
System.out.println("剩余用户数为: " + c);
}
}
控制台输出如下: