Hibernate & JPA
1、JPA
The full name is Java Persistence API, which describes the object-relational table mapping relationship through JDK 5.0 annotations or XML, and persists the entity objects at runtime to the database.
There are two reasons for the emergence of JPA:
First, to simplify the development of object persistence for existing Java EE and Java SE applications;
second, Sun hopes to integrate ORM technology to achieve the unification of the persistence field.
Technologies provided by JPA:
1) ORM mapping metadata: JPA supports XML and JDK 5.0 annotations in two forms of metadata. The metadata describes the mapping relationship between objects and tables, and the framework persists entity objects to database tables accordingly;
2) JPA API: used to manipulate entity objects, perform CRUD operations, the framework does everything for us in the background, and developers are freed from cumbersome JDBC and SQL codes.
3) Query language: query data through an object-oriented rather than database-oriented query language to avoid tight coupling of program SQL statements.
2. JPA & Hibernate relationship
JPA needs Provider to realize its functions, and Hibernate is a strong one in JPA Provider. Functionally, JPA is now a subset of Hibernate functionality. It can be simply understood that JPA is the standard interface and Hibernate is the implementation. Hibernate is mainly implemented through three components, hibernate-annotation, hibernate-entitymanager and hibernate-core.
1) Hibernate-annotation is the basis for Hibernate to support annotation mode configuration, which includes standard JPA annotation and annotation of Hibernate's own special functions.
2) hibernate-core is the core implementation of Hibernate, providing all the core functions of Hibernate.
3) hibernate-entitymanager implements standard JPA, which can be regarded as an adapter between hibernate-core and JPA. It does not directly provide ORM functions, but encapsulates hibernate-core so that Hibernate conforms to the JPA specification .
In general, JPA is the specification, Hibernate is the framework, JPA is the persistence specification, and Hibernate implements JPA.
3. Overview of JPA
1 Overview
The location of JPA in the application is shown in the following figure:
JPA maintains a Persistence Context (persistence context) in which the entity's life cycle is maintained. It mainly includes three aspects:
- ORM metadata. JPA supports two forms of annotation or xml to describe object-relational mapping.
- Entity manipulation API. Implement CRUD operations on entity objects.
-
query language. The object-oriented query language JPQL (Java Persistence Query Language) is agreed.
cfg.Configuration | Persistence | Read configuration information |
SessionFactory | EntityManagerFactory | Factory class for creating session/entity managers |
Session | EntityManager | Provides entity manipulation API, manages transactions, and creates queries |
Transaction | EntityTransaction | management affairs |
Query | Query | execute query |
2. Entity life cycle
Entity life cycle is a very important concept in JPA, which describes the state transition of entity objects from creation to control, from deletion to free. The operation of the entity is mainly to change the state of the entity.
The life cycle of an entity in JPA is as follows:
- New, a newly created entity object without a primary key (identity) value
- Managed, the object is in the Persistence Context (persistence context), managed by the EntityManager
- Detached,对象已经游离到Persistence Context之外,进入Application Domain
-
Removed, 实体对象被删除
3、实体关系映射(ORM)
1)基本映射
Class
|
Table
|
@Entity
|
@Table(name="table
name")
|
property | column | – | @Column(name = "columnname") |
property | primary key | @Id | @GeneratedValue 详见ID生成策略 |
property | NONE | @Transient |
2)映射关系
JPA定义了one-to-one、one-to-many、many-to-one、many-to-many 4种关系。
对于数据库来说,通常在一个表中记录对另一个表的外键关联;对应到实体对象,持有关联数据的一方称为owning-side,另一方称为inverse-side。
为了编程的方便,我们经常会希望在inverse-side也能引用到owning-side的对象,此时就构建了双向关联关系。 在双向关联中,需要在inverse-side定义mappedBy属性,以指明在owning-side是哪一个属性持有的关联数据。
对关联关系映射的要点如下:
one-to-one | @OneToOne | @OneToOne(mappedBy="othersideName") |
one-to-many / many-to-one | @ManyToOne | @OneToMany(mappedBy="xxx") |
many-to-many | @ManyToMany | @ManyToMany(mappedBy ="xxx") |
其中 many-to-many关系的owning-side可以使用@JoinTable声明自定义关联表,比如Book和Author之间的关联表:
@JoinTable(name = "BOOKAUTHOR", joinColumns = { @JoinColumn(name = "BOOKID", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "AUTHORID", referencedColumnName = "id") })
关联关系还可以定制延迟加载和级联操作的行为(owning-side和inverse-side可以分别设置):
通过设置fetch=FetchType.LAZY 或 fetch=FetchType.EAGER来决定关联对象是延迟加载或立即加载。
通过设置cascade={options}可以设置级联操作的行为,其中options可以是以下组合:
- CascadeType.MERGE 级联更新
- CascadeType.PERSIST 级联保存
- CascadeType.REFRESH 级联刷新
- CascadeType.REMOVE 级联删除
-
CascadeType.ALL 级联上述4种操作
4、事件及监听
通过在实体的方法上标注@PrePersist,@PostPersist等声明即可在事件发生时触发这些方法。
四、JPA应用
1、Dependencies
2、JPA提供的接口
主要来看看Spring Data JPA提供的接口,也是Spring Data JPA的核心概念:
public interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {
Iterable<T> findAll(Sort sort);
Page<T> findAll(Pageable pageable);
}
public interface JpaSpecificationExecutor<T>{
T findOne(Specification<T> spec);
List<T> findAll(Specification<T> spec);
Page<T> findAll(Specification<T> spec, Pageable pageable);
List<T> findAll(Specification<T> spec, Sort sort);
long count(Specification<T> spec);
}
3、查询语言
3.1 根据名称判别
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3.2 @Query
3.3 复杂查询 JpaSpecificationExecutor
Criteria 查询:是一种类型安全和更面向对象的查询
这个接口基本是围绕着Specification接口来定义的, Specification接口中只定义了如下一个方法:
Criteria查询
实例:
ImTeacher.java
@Entity
@Table(name = "im_teacher")
public class ImTeacher implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "teacher_id")
private int teacherId;
@Column(name = "name")
private String name = "";
@Column(name = "age")
private int age;
@Column(name = "sex")
private String sex = "";
...
}
ImTeacherDao.java
public interface ImTeacherDao extends PagingAndSortingRepository<ImTeacher, Integer>,JpaSpecificationExecutor{
...
}
@Service
public class ImTeacherDaoService {
@Autowired
ImTeacherDao imTeacherDao;
/**
* 复杂查询测试
* @param page
*/
public Page<ImTeacher> findBySepc(int page, int size){
PageRequest pageReq = this.buildPageRequest(page, size);
Page<ImTeacher> imTeachers = this.imTeacherDao.findAll(new MySpec(), pageReq);
return imTeachers;
}
/**
* 建立分页排序请求
*/
private PageRequest buildPageRequest(int page, int size) {
Sort sort = new Sort(Direction.DESC,"age");
return new PageRequest(page,size, sort);
}
private class MySpec implements Specification<ImTeacher>{
@Override
public Predicate toPredicate(Root<ImTeacher> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//1.混合条件查询
Path<String> exp1 = root.get("name");
Path<String> exp2 = root.get("age");
query.where(cb.like(exp1, "%王%"),cb.equal(exp2, "45"));
//2.多表查询
/*Join<ImTeacher,ImStudent> join = root.join("imStudent", JoinType.INNER);
Path<String> exp3 = join.get("name");
return cb.like(exp3, "%jy%");*/
return null;
}
}
}
3.4 分页
上个实例的发杂查询已经带有分页,若实例的DAO接口有继承PagingAndSortingRepository接口,则可以直接调用
Page<ImTeacher> impeacher = imTeacherDao.findAll(new PageRequest(1,20));
3.5 联表查询
@Entity
@Table(name = "im_student")
public class ImStudent {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "student_id")
private int studentId;
@Column(name = "name")
private String name = "";
@Column(name = "age")
private int age;
@Column(name = "sex")
private String sex = "";
@Column(name = "teacher_id")
private int teacherId;
@ManyToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH})
@JoinColumn(name="teacher_id", referencedColumnName="id", insertable=false, updatable=false)
private ImTeacher imTeacher;
...
}
2)在ImTeacher.java中添加
@OneToMany(mappedBy="imTeacher",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
private Set<ImStudent> imStudent = new HashSet<ImStudent>();
...
3)根据学生名字查出其老师信息
@Query("SELECT teacher FROM ImTeacher teacher JOIN teacher.imStudent student WHERE student.name=:name")
ImTeacher findByStuName(@Param("name") String name);
根据老师名字查出其学生列表
@Query("SELECT student FROM ImStudent student JOIN student.imTeacher teacher WHERE teacher.name = :name")
Set<ImStudent> findByStudByTeaName(@Param("name") String name);
四、总结
1、Hibernate的DAO层开发比较简单,对于刚接触ORM的人来说,能够简化开发工程,提高开发速度。
2、Hibernate对对象的维护和缓存做的很好,对增删改查的对象的维护要方便。
3、Hibernate数据库移植性比较好。
4、Hibernate功能强大,如果对其熟悉,对其进行一定的封装,那么项目的整个持久层代码会比较简单。