Hibernate ORM 5.3 实现了 JPA 2.2 标准。在接下来的几周内,我们将介绍 JPA 2.2 引入的各种特性。
如果 Hibernate ORM 5.2 已经增加了对特定 Hibernate 注解的支持,JPA 2.2 将允许您使用特定 JPA 的注解做同样的事情。
在本文中,我们将看到重复注解功能将如何简化您的实体映射。
JPA 2.2 之前
现在,在 JPA 2.2 之前,如果您想使用多个 @NamedQuery
注解,您还必须使用 @NamedQueries
。
@NamedQueries({
@NamedQuery(
name = "get_person_by_name",
query = "select p from Person p where name = :name"
),
@NamedQuery(
name = "get_read_only_person_by_name",
query = "select p from Person p where name = :name",
hints = {
@QueryHint(
name = "org.hibernate.readOnly",
value = "true"
)
}
)
})
@Entity
public class Person {
...
}
JPA 2.2
JPA 2.2 增加了支持 Java 8 中引入的 重复注解 功能。
如果您打开 JPA 2.2 的 @NamedQuery
注解,源代码看起来如下所示
@Repeatable(NamedQueries.class)
@Target({TYPE})
@Retention(RUNTIME)
public @interface NamedQuery {
/**
* (Required) The name used to refer to the query with the {@link EntityManager}
* methods that create query objects.
*/
String name();
/** (Required)
* The query string in the Java Persistence query language.
*/
String query();
/**
* (Optional) The lock mode type to use in query execution. If a <code>lockMode</code>
* other than <code>LockModeType.NONE</code> is specified, the query must be executed in
* a transaction and the persistence context joined to the transaction.
* @since Java Persistence 2.0
*/
LockModeType lockMode() default NONE;
/** (Optional) Query properties and hints. May include
* vendor-specific query hints.
*/
QueryHint[] hints() default {};
}
注意第一行,@Repeatable(NamedQueries.class)
,它告诉我们在重复使用 @NamedQuery
多次时,应该使用 @NamedQueries
注解。
所以,在幕后,即使我们没有声明 @NamedQueries
注解,Java 也会使用它。
现在,使用重复注解支持,我们可以将 Person
实体映射修改如下
@NamedQuery(
name = "get_person_by_name",
query = "select p from Person p where name = :name"
)
@NamedQuery(
name = "get_read_only_person_by_name",
query = "select p from Person p where name = :name",
hints = {
@QueryHint(
name = "org.hibernate.readOnly",
value = "true"
)
}
)
@Entity
public class PersonRepeatingAnnotation {
...
}
不是更好了吗?