jpa 概述
全称Java Persistence API,通过JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中
JPA提供的技术:
1)ORM映射元数据:JPA支持XML和JDK 5.0注解两种元数据的形式,元数据描述对象和表之间的映射关系,框架据此将实体对象持久化到数据库表中;
2)JPA 的API:用来操作实体对象,执行CRUD操作,框架在后台替我们完成所有的事情,开发者从繁琐的JDBC和SQL代码中解脱出来。
3)查询语言:通过面向对象而非面向数据库的查询语言查询数据,避免程序的SQL语句紧密耦合。
jpa 和hibernate的关系
JPA是规范,Hibernate是框架,JPA是持久化规范,而Hibernate实现了JPA。
在springboot中的 jpa的使用
##实体对象
实体关系映射(ORM)
对象端 | 数据库端 | annotion | |
---|---|---|---|
Class | Table | @Entity @Table(name=“tablename”) | |
property | column | @Column(name = “columnname”) | |
property | primary key | @Id @GeneratedValue 详见ID生成策略 |
@Table(name="t_dept")
@Entity
public class Dept {
@Id
@GeneratedValue
int did;
String dname;
映射关系
JPA定义了
one-to-one、one-to-many、many-to-one、many-to-many 4种关系。
JPA提供的接口
JpaRepository,最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型
CrudRepository :是Repository的子接口,提供CRUD的功能
PagingAndSortingRepository:是CrudRepository的子接口,添加分页和排序的功能
接口举例
@Repository
public interface JpaDao extends JpaRepository<RiCheng, Integer> {
Page<RiCheng> findGoodsListBySnameContaining(String name,Pageable page);
}
jap中的默认查询方法
Keyword | Sample | JPQL snippet |
---|---|---|
Keyword | Sample | JPQL snippet |
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 | findByAgeIsNull | … 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 %) |
Containing1 | 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 age) | … where x.age not in ?1 |
TRUE | findByActiveTrue() | … where x.active = true |
FALSE | findByActiveFalse() | … where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(x.firstame) = UPPER(?1) |
jpa的分页
设置分页
PageRequest pageRequest = PageRequest.of(1, 3);
传参:Page findGoodsListBySnameContaining(String name,Pageable page);