[转]Hibernate对Annotation的扩展

Hibernate Annotation Extensions

Hibernate 3.1 offers a variety of additional annotations that you
can mix/match with your EJB 3 entities. They have been designed as a
natural extension of EJB3 annotations.

Hibernate 3.1 提供了多种附加的注解,这些注解可以与EJB3的实体混合/匹配使用。
他们被设计成EJB3注解的自然扩展。

To empower the EJB3 capabilities, hibernate provides specific
annotations that match hibernate features. The
org.hibernate.annotations package contains all
these annotations extensions.

为了强化EJB3的能力,Hibernate提供了与其自身特性相吻合的特殊注解。
org.hibernate.annotations 包已包含了所有的这些注解扩展。

Entity

You can fine tune some of the actions done by Hibernate on
entities beyond what the EJB3 spec offers.

你可以在EJB3规范所能提供的能力之外,就Hibernate对实体所作的一些操作进行优化。

@org.hibernate.annotations.Entity adds
additional metadata that may be needed beyond what is defined in the
standard @Entity

mutable: whether this entity is mutable or not

dynamicInsert: allow dynamic SQL for inserts

dynamicUpdate: allow dynamic SQL for updates

selectBeforeUpdate: Specifies that Hibernate should never perform an SQL UPDATE unless it is certain that an object is actually modified.

polymorphism: whether the entity polymorphism is of PolymorphismType.IMPLICIT (default) or PolymorphismType.EXPLICIT

persister: allow the overriding of the default persister implementation

optimisticLock: optimistic locking strategy (OptimisticLockType.VERSION, OptimisticLockType.NONE, OptimisticLockType.DIRTY or OptimisticLockType.ALL)

@org.hibernate.annotations.Entity
追加了可能需要的额外的元数据,
而这些元数据超出了标准@Entity 中所定义的元数据。

mutable: 此实体是否为可变的

dynamicInsert: 用动态SQL新增

dynamicUpdate: 用动态SQL更新

selectBeforeUpdate: 指明Hibernate从不运行SQL UPDATE除非能确定对象的确已被修改

polymorphism: (指出)实体多态是PolymorphismType.IMPLICIT(默认)还是PolymorphismType.EXPLICIT

persister: allow the overriding of the default persister implementation

允许对默认持久实现(persister implementation)的覆盖

optimisticLock: 乐观锁策略(OptimisticLockType.VERSION, OptimisticLockType.NONE, OptimisticLockType.DIRTY 或 OptimisticLockType.ALL)

note

@javax.persistence.Entity is still mandatory,
@org.hibernate.annotations.Entity is not a replacement.

note

@javax.persistence.Entity仍是必选的(mandatory),
@org.hibernate.annotations.Entity不是取代品。

Here are some additional Hibernate annotation extensions

以下是一些附加的Hibernate注解扩展:

@org.hibernate.annotations.BatchSize allows you
to define the batch size when fetching instances of this entity ( eg.
@BatchSize(size=4) ). When loading a given entity,
Hibernate will then load all the uninitialized entities of the same type
in the persistence context up to the batch size.

@org.hibernate.annotations.BatchSize 允许你定义批量抓取该实体的实例数量(如:@BatchSize(size=4) )。
当加载一特定的实体时,Hibernate将加载在持久上下文中未经初始化的同类型实体,直至批量数量(上限)。

@org.hibernate.annotations.Proxy defines the
laziness attributes of the entity. lazy (default to true) define whether
the class is lazy or not. proxyClassName is the interface used to
generate the proxy (default is the class itself).

@org.hibernate.annotations.Proxy
定义了实体的延迟属性。Lazy(默认为true)定义了类是否为延迟(加载)。
proxyClassName是用来生成代理的接口(默认为该类本身)。

@org.hibernate.annotations.Where defines an
optional SQL WHERE clause used when instances of this class is
retrieved.

@org.hibernate.annotations.Where 定义了当获取类实例时所用的SQL WHERE子句(该SQL WHERE子句为可选)。

@org.hibernate.annotations.Check defines an
optional check constraints defined in the DDL statetement.

@org.hibernate.annotations.Check
定义了在DDL语句中定义的合法性检查约束(该约束为可选)。

@OnDelete(action=OnDeleteAction.CASCADE) on
joined subclasses: use a SQL cascade delete on deletion instead of the
regular Hibernate mechanism.

@OnDelete(action=OnDeleteAction.CASCADE)
定义于被连接(joined)的子类:在删除时使用SQL级连删除,而非通常的Hibernate删除机制。

@Table(name="tableName", indexes = {
@Index(name="index1", columnNames={"column1", "column2"} ) } )

creates the defined indexes on the columns of table tableName. This can
be applied on the primary table or any secondary table. The
@Tables annotation allows your to apply indexes on
different tables. This annotation is expected where
@javax.persistence.Table or
@javax.persistence.SecondaryTable (s) occurs.
@org.hibernate.annotations.Table is a complement, not
a replacement to @javax.persistence.Table

@Table(name="tableName", indexes = {
@Index(name="index1", columnNames={"column1", "column2"} ) } )
在tableName表的字段上创建定义好的索引。该注解可以被应用于关键表或者是其他次要的表。
@Tables 注解允许你在不同的表上应用索引。
此注解预期在使用
@javax.persistence.Table
@javax.persistence.SecondaryTable 的地方中出现.
@org.hibernate.annotations.Table 是对
@javax.persistence.Table 的补充而不是它的替代品。

programlisting

@Entity
@BatchSize(size=5)
@org.hibernate.annotations.Entity(
selectBeforeUpdate = true,
dynamicInsert = true, dynamicUpdate = true,
optimisticLock = OptimisticLockType.ALL,
polymorphism = PolymorphismType.EXPLICIT)
@Where(clause="1=1")
@org.hibernate.annotations.Table(name="Forest", indexes = { @Index(name="idx", columnNames = { "name", "length" } ) } )
public class Forest { ... }

programlisting

@Entity
@Inheritance(
strategy=InheritanceType.JOINED
)
public class Vegetable { ... }

@Entity
@OnDelete(action=OnDeleteAction.CASCADE)
public class Carrot extends Vegetable { ... }

Identifier

@org.hibernate.annotations.GenericGenerator
allows you to define an Hibernate specific id
generator.

@org.hibernate.annotations.GenericGenerator
允许你定义一个Hibernate特定的id生成器。

programlisting

@Id @GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
public String getId() {

@Id @GeneratedValue(generator="hibseq")
@GenericGenerator(name="hibseq", strategy = "seqhilo",
parameters = {
@Parameter(name="max_lo", value = "5"),
@Parameter(name="sequence", value="heybabyhey")
}
)
public Integer getId() {

strategy is the short name of an Hibernate3
generator strategy or the fully qualified class name of an
IdentifierGenerator implementation. You can add
some parameters through the parameters
attribute

strategy 可以是Hibernate3生成器策略的简称,或者是一个IdentifierGenerator 实现的(带包路径的)全限定类名。
你可以通过parameters 属性增加一些参数。

Property

Access type

The access type is guessed from the position of
@Id or @EmbeddedId in the entity
hierarchy. Sub-entities, embedded objects and mapped superclass
inherit the access type from the root entity.

访问类型是根据@Id@EmbeddedId 在实体继承层次中所处的位置推演而得的。子实体(Sub-entities),内嵌对象和被映射的父类均从根实体(root entity)继承访问类型。

In Hibernate, you can override the access type to:

在Hibernate中,你可以把访问类型覆盖成:

use a custom access type strategy

fine tune the access type at the class level or at the
property level

使用定制的访问类型策略

优化类级别或属性级别的访问类型

An @AccessType annotation has been introduced to support this
behavior. You can define the access type on

为支持这种行为,Hibernate引入了@AccessType注解。你可以对以下元素定义访问类型:

an entity

a superclass

an embeddable object

a property

实体

父类

可内嵌的对象

属性

The access type is overriden for the annotated element, if
overriden on a class, all the properties of the given class inherit
the access type. For root entities, the access type is considered to
be the default one for the whole hierarchy (overridable at class or
property level).

被注解元素的访问类型会被覆盖,若覆盖是在类级别上,则所有的属性继承访问类型。
对于根实体,其访问类型会被认为是整个继承层次中的缺省设置(可在类或属性一级覆盖)。

If the access type is marked as "property", the getters are
scanned for annotations, if the access type is marked as "field", the
fields are scanned for annotations. Otherwise the elements marked with
@Id or @embeddedId are scanned.

若访问类型被标以"property",则Hibernate会扫描getter方法的注解,若访问类型被标以"field",则扫描字段的注解。否则,扫描标为@Id或@embeddedId的元素。
You can override an access type for a property, but the element
to annotate will not be influenced: for example an entity having
access type field , can annotate a field with
@AccessType("property") , the access type will then
be property for this attribute, the the annotations still have to be
carried on the field.

你可以覆盖某个属性(property)的访问类型,但是受注解的元素将不受影响:例如一个具有field访问类型的实体,(我们)可以将某个字段 标注为 @AccessType("property"),则该字段的访问类型随之将成为property,但是其他字段上依然需要携带注解。

If a superclass or an embeddable object is not annotated, the
root entity access type is used (even if an access type has been
define on an intermediate superclass or embeddable object). The
russian doll principle does not apply.

若父类或可内嵌的对象没有被注解,则使用根实体的访问类型(即使已经在非直系父类或可内嵌对象上定义了访问类型)。此时俄罗斯套娃(Russian doll)原理就不再适用。(译注:俄罗斯套娃(матрёшка或 матрешка)是俄罗斯特产木制玩具,一般由多个一样图案的空心木娃娃一个套一个组成,最多可达十多个,通常为圆柱形,底部平坦可以直立。)

programlisting

@Entity
public class Person implements Serializable {
@Id @GeneratedValue //access type field
Integer id;

@Embedded
@AttributeOverrides({
@AttributeOverride(name = "iso2", column = @Column(name = "bornIso2")),
@AttributeOverride(name = "name", column = @Column(name = "bornCountryName"))
})
Country bornIn;
}

@Embeddable
@AccessType("property") //override access type for all properties in Country
public class Country implements Serializable {
private String iso2;
private String name;

public String getIso2() {
return iso2;
}

public void setIso2(String iso2) {
this.iso2 = iso2;
}

@Column(name = "countryName")
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

Formula

Sometimes, you want the Database to do some computation for you
rather than in the JVM, you might also create some kind of virtual
column. You can use a SQL fragment (aka formula) instead of mapping a
property into a column. This kind of property is read only (its value
is calculated by your formula fragment).

Sometimes, you want the Database to do some computation for you
rather than in the JVM, you might also create some kind of virtual
column. You can use a SQL fragment (aka formula) instead of mapping a
property into a column. This kind of property is read only (its value
is calculated by your formula fragment).

有时候,你想让数据库,而非JVM,来替你完成一些计算,也可能想创建某种虚拟字段(译注:即数据库视图)。你可以使用一段SQL(亦称为公式),而不是将属性映射到(物理)字段。 这种属性是只读的(属性值由公求得)。

programlisting

@Formula("obj_length * obj_height * obj_width")
public long getObjectVolume()

The SQL fragment can be as complex as you want avec even include
subselects.

SQL片段可以是任意复杂的,甚至可包含子查询。

Type

@org.hibernate.annotations.Type overrides the
default hibernate type used: this is generally not necessary since the
type is correctly inferred by Hibernate. Please refer to the Hibernate
reference guide for more informations on the Hibernate types.

@org.hibernate.annotations.Type
覆盖了Hibernate所用的默认类型:这通常不是必须的,因为类型可以由Hibernate正确推得。
关于Hibernate类型的详细信息,请参考Hibernate使用手册。

@org.hibernate.annotations.TypeDef and
@org.hibernate.annotations.TypeDefs allows you to
declare type definitions. These annotations are placed at the class or
package level. Note that these definitions will be global for the
session factory (even at the class level) and that type definition has
to be defined before any usage.

@org.hibernate.annotations.TypeDef
@org.hibernate.annotations.TypeDefs 允许你来声明类型定义。
这些注解被置于类或包一级。注意,对session factory来说,
这些定义将是全局的(即使定义于类一级),并且类型定义必须先于任何使用。

programlisting

@TypeDefs(
{
@TypeDef(
name="caster",
typeClass = CasterStringType.class,
parameters = {
@Parameter(name="cast", value="lower")
}
)
}
)
package org.hibernate.test.annotations.entity;

...
public class Forest {
@Type(type="caster")
public String getSmallText() {
...
}

When using composite user type, you will have to express column
definitions. The @Columns has been introduced for
that purpose.

当使用组合的用户自定义类型时,你必须自己来表达字段定义。
@Columns 就是为了此目的而引入的。

programlisting

@Type(type="org.hibernate.test.annotations.entity.MonetaryAmountUserType")
@Columns(columns = {
@Column(name="r_amount"),
@Column(name="r_currency")
})
public MonetaryAmount getAmount() {
return amount;
}

public class MonetaryAmount implements Serializable {
private BigDecimal amount;
private Currency currency;
...
}

Index

You can define an index on a particular column using the
@Index annotation on a one column property, the
columnNames attribute will then be ignored

通过在字段属性(property)上使用@Index 注解,
可以在特定字段上定义索引,columnNames属性(attribute)将随之被忽略。

programlisting

@Column(secondaryTable="Cat1")
@Index(name="story1index")
public String getStoryPart1() {
return storyPart1;
}

Inheritance

SINGLE_TABLE is a very powerful strategy but sometimes, and
especially for legacy systems, you cannot add an additional
discriminator column. For that purpose Hibernate has introduced the
notion of discriminator formula:
@DiscriminatorFormula is a replacement of
@DiscriminatorColumn and use a SQL fragment as a
formula for discriminator resolution (no need to have a dedicated
column).

SINGLE_TABLE 是个功能强大的策略,但有时,特别对遗留系统而言,
是无法加入一个额外的识别符字段(discriminator column)。
由此,Hibernate引入了识别符公式(discriminator formula)的概念:
@DiscriminatorFormula@DiscriminatorColumn 的替代品,
它使用SQL片段作为识别符解决方案的公式( 不需要有一个专门的字段)。

programlisting

@Entity
@DiscriminatorForumla("case when forest_type is null then 0 else forest_type end")
public class Forest { ... }

Association related annotations

By default, when Hibernate cannot resolve the association because
the expected associated element is not in database (wrong id on the
association column), an exception is raised by Hibernate. This might be
inconvenient for lecacy and badly maintained schemas. You can ask
Hibernate to ignore such elements instead of raising an exception using
the @NotFound annotation. This annotation can be used
on a @OneToOne (with FK),
@ManyToOne , @OneToMany or
@ManyToMany association.

默认情况下,当预期的被关联元素不在数据库中(关乎关联字段的id错误),致使Hiberante无法解决关联性问题时,Hibernate就会抛出异常。
这对遗留schema和历经拙劣维护的schema而言,这或有许多不便。
此时,你可用 @NotFound 注解让Hibernate略过这样的元素而不是抛出异常。
该注解可用于 @OneToOne (有外键)、 @ManyToOne
@OneToMany @ManyToMany 关联。

programlisting

@Entity
public class Child {
...
@ManyToOne
@NotFound(action=NotFoundAction.IGNORE)
public Parent getParent() { ... }
...
}

Collection related annotations

Parameter annotations

It is possible to set

the batch size for collections using @BatchSize

the where clause, using @Where

the check clause, using @Check

the SQL order by clause, using @OrderBy

the delete cascade strategy through @OnDelete(action=OnDeleteAction.CASCADE)

以下是可能的设置方式

用@BatchSizebatch设置集合的batch大小

用@Where注解设置Where子句

用注解@Check来设置check子句

用注解@OrderBy来设置SQL的order by子句

利用@OnDelete(action=OnDeleteAction.CASCADE) 注解设置级连删除策略

You can also declare a sort comparator. Use the
@Sort annotation. Expressing the comparator type
you want between unsorted, natural or custom comparator. If you want
to use your own comparator implementation, you'll also have to express
the implementation class using the comparator
attribute.

你也可以利用@Sort 注解定义一个排序比较器(sort comparator),表明希望的比较器类型,无序、自然顺序或自定义排序,三者择一。若你想用你自己实现的comparator,
你还需要利用comparator 属性(attribute)指明实现类。

programlisting

@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="CUST_ID")
@Sort(type = SortType.COMPARATOR, comparator = TicketComparator.class)
@Where(clause="1=1")
@OnDelete(action=OnDeleteAction.CASCADE)
public SortedSet<Ticket> getTickets() {
return tickets;
}

Please refer to the previous descriptions of these annotations
for more informations.

关于这些注解更详细的信息,请参阅此前的描述。

Extra collection types

Beyond EJB3, Hibernate Annotations supports true
List and Array . Map your
collection the same way as usual and add the
@IndexColumn . This annotation allows you to
describe the column that will hold the index. You can also declare the
index value in DB that represent the first element (aka as base
index). The usual value is 0 or
1 .

比EJB3更胜一筹的是,Hibernate Annotations支持真正的ListArray
映射集合的方式和以前完全一样,只不过要新增@IndexColumn 注解。该注解允许你指明存放索引值的字段。你还可以定义代表数据库中首个元素的索引值(亦称为索引基数)。常见取值为01

programlisting

@OneToMany(cascade = CascadeType.ALL)
@IndexColumn(name = "drawer_position", base=1)
public List<Drawer> getDrawers() {
return drawers;
}

note

If you forgot to set @IndexColumn , the bag
semantic is applied

假如你忘了设置@IndexColumn ,Hibernate会采用bag语义(译注:即允许重复元素的无序集合)。

Hibernate Annotations also supports collections of core types
(Integer, String, Enums, ...), collections of embeddable objects and
even arrays of primitive types. This is known as collection of
elements.

Hibernate Annotations还支持核心类型集合(Integer, String, Enums, ......)、
可内嵌对象的集合,甚至基本类型数组。这就是所谓的元素集合。

A collection of elements as to be annotated as
@CollectionOfElements (as a replacement of
@OneToMany ) To define the collection table, the
@JoinTable annotation is used on the association
property, joinColumns defines the join columns
between the entity primary table and the collection table
(inverseJoincolumn is useless and should be left empty). For
collection of core types or array of primitive types, you can override
the element column definition using a @Column on
the association property. You can also override the columns of a
collection of embeddable object using
@AttributeOverride .

元素集合可用@CollectionOfElements来注解(作为@OneToMany的替代)。
为了定义集合表(译注:即存放集合元素的表,与下面提到的主表对应),要在关联属性上使用@JoinTable注解,joinColumns定义了介乎实体主表与集合表之间的连接字段(inverseJoincolumn是无效的且其值应为空)。
对于核心类型的集合或基本类型数组,你可以在关联属性上用@Column 来覆盖存放元素值的字段的定义。你还可以用@AttributeOverride来覆盖存放可内嵌对象的字段的定义。

programlisting

@Entity
public class Boy {
private Integer id;
private Set<String> nickNames = new HashSet<String>();
private int[] favoriteNumbers;
private Set<Toy> favoriteToys = new HashSet<Toy>();
private Set<Character> characters = new HashSet<Character>();

@Id @GeneratedValue
public Integer getId() {
return id;
}

@CollectionOfElements
public Set<String>
getNickNames() {
return nickNames;
}

@CollectionOfElements
@JoinTable(
table=@Table(name="BoyFavoriteNumbers"),
joinColumns = @JoinColumn(name="BoyId")
)
@Column(name="favoriteNumber", nullable=false)

@IndexColumn(name="nbr_index")
public int[] getFavoriteNumbers() {
return favoriteNumbers;
}

@CollectionOfElements
@AttributeOverride( name="serial", column=@Column(name="serial_nbr") )

public Set<Toy> getFavoriteToys() {
return favoriteToys;
}

@CollectionOfElements
public Set<Character>
getCharacters() {
return characters;
}
...
}

public enum Character {
GENTLE,
NORMAL,
AGGRESSIVE,
ATTENTIVE,
VIOLENT,
CRAFTY
}

@Embeddable
public class Toy {
public String name;
public String serial;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSerial() {
return serial;
}

public void setSerial(String serial) {
this.serial = serial;
}

public boolean equals(Object o) {
if ( this == o ) return true;
if ( o == null || getClass() != o.getClass() ) return false;

final Toy toy = (Toy) o;

if ( !name.equals( toy.name ) ) return false;
if ( !serial.equals( toy.serial ) ) return false;

return true;
}

public int hashCode() {
int result;
result = name.hashCode();
result = 29 * result + serial.hashCode();
return result;
}
}

note

Previous versions of Hibernate Annotations used the
@OneToMany to mark a collection of elements. Due
to semantic inconsistencies, we've introduced the annotation
@CollectionOfElements . Marking collections of
elements the old way still work but is considered deprecated and is
going to be unsupported in future releases

旧版的Hibernate Annotations用@OneToMany 来标识集合元素。
由于语义矛盾,我们引入了@CollectionOfElements 注解。
@OneToMany 来标识集合元素的这种旧有方式目前尚有效,但是不推荐使用,而且在以后的发布版本中不再支持这种方式。

Cache

In order to optimize your database accesses, you can activave the
so called second level cache of Hibernate. This cache is configurable on
a per entity and per collection basis.

为了优化数据库访问,你可以激活所谓的Hibernate二级缓存。该缓存是可以按每个实体和集合进行配置的。

@org.hibernate.annotations.Cache defines the
caching strategy and region of a given second level cache. This
annotation can be applied on the root entity (not the sub entities), and
on the collections.

@org.hibernate.annotations.Cache 定义了缓存策略及给定的二级缓存的范围。此注解适用于根实体(非子实体),还有集合。

programlisting

@Entity
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Forest { ... }

programlisting

@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="CUST_ID")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public SortedSet<Ticket> getTickets() {
return tickets;
}

programlisting

@Cache(
CacheConcurrencyStrategy usage();
String region() default "";
String include() default "all";
)

usage: the given cache concurrency strategy (NONE,
READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)

region (optional): the cache region (default to the fqcn of
the class or the fq role name of the collection)

include (optional): all to include all
properties, non-lazy to only include non lazy properties (default
all).

usage: 给定缓存的并发策略(NONE,
READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)

region (可选的):缓存范围(默认为类的全限定类名或是集合的全限定角色名)

include (可选的):值为all时包括了所有的属性(proterty),
为non-lazy时仅含非延迟属性(默认值为all)

Filters

Hibernate has the notion of data filter that can be applied at
runtime on a given session. Those filters has to be defined
first.

Hibernate具有数据过滤器的概念,可在运行期应用于一个给定的session。过滤器需要事先定义好。

@org.hibernate.annotations.FilterDef or
@FilterDefs define filter definition(s) used by
filter(s) using the same name. A filter definition has a name() and an
array of parameters(). A @ParamDef has a name and a
type. You can also define a defaultCondition() parameter for a given
@filterDef to set the default condition to use when
none are defined in the @Filter . A
@FilterDef (s) can be defined at the class or package
level.

@org.hibernate.annotations.FilterDef
@FilterDefs 定义过滤器声明,为同名过滤器所用。
过滤器声明带有一个name()和一个parameters()数组,@ParamDef包含name和type,你还可以为给定的@filterDef定义一个defaultCondition()参数,当@Filter中没有任何定义时,可使用该参数定义缺省条件。
@FilterDef
(s)可以在类或包一级进行定义。

We now need to define the SQL filter clause applied to either the
entity load or the collection load. @Filter is used
and placed either on the entity or the collection element

现在我们来定义应用于实体或集合加载时的SQL过滤器子句。我们使用@Filter ,并将其置于实体或集合元素上。

programlisting

@Entity
@FilterDef(name="minLength", parameters={ @ParamDef( name="minLength", type="integer" ) } )
@Filters( {
@Filter(name="betweenLength", condition=":minLength <= length and :maxLength >= length"),
@Filter(name="minLength", condition=":minLength <= length")
} )
public class Forest { ... }

Queries

Since Hibernate has more features on named queries than the one
defined in the EJB3 specification,
@org.hibernate.annotations.NamedQuery ,
@org.hibernate.annotations.NamedQueries ,
@org.hibernate.annotations.NamedNativeQuery and
@org.hibernate.annotations.NamedNativeQueries have
been introduced. They add some attributes to the standard version and
can be used as a replacement:

由于Hibernate引入了
@org.hibernate.annotations.NamedQuery ,
@org.hibernate.annotations.NamedQueries ,
@org.hibernate.annotations.NamedNativeQuery
@org.hibernate.annotations.NamedNativeQueries 命名式查询,因此Hibernate在命名式查询上比EBJ3规范中所定义的命名式查询提供了更多的特性。
他们在标准版中添加了可作为替代品的一些属性(attributes):

flushMode: define the query flush mode (Always, Auto, Commit
or Never)

cacheable: whether the query should be cached or not

cacheRegion: cache region used if the query is cached

fetchSize: JDBC statement fetch size for this query

timeout: query time out

callable: for native queries only, to be set to true for
stored procedures

comment: if comments are activated, the comment seen when the
query is sent to the database.

cacheMode: Cache interaction mode (get, ignore, normal, put or
refresh)

readOnly: whether or not the elements retrievent from the
query are in read only mode.

flushMode: 定义查询的刷新模式(Always, Auto, Commit或Never)

cacheable: 查询该不该被缓存

cacheRegion: 若查询已被缓存时所用缓存的范围

fetchSize: 针对该查询的JDBC statement单次获取记录的数目

timeout: 查询超时

callable: 仅用于本地化查询(native query),对于存储过程设为true

comment: 一旦激活注释功能,我们会在向数据库交送查询请求时看到注释

cacheMode: 缓存交护模式(get, ignore,normal,或refresh)

readOnly: 不管是否从查询获取元素都是在只读模式下

Note, that the EJB3 public final draft has introduced the notion
of @QueryHint , which is probably a better way to
define those hints.

注意,EJB3已公开的最终草案中引入了@QueryHint 的概念,
这可能是定义hints更好的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值