分享

Chapter 2.实体 Beans (II)

 bwg 2007-07-25

Chapter 2.实体 Beans (II)

09:46上午 三月 19, 2006 in category HA by icess

Chapter 2. 实体 Beans 2

2.2.5.4. 机联持久化 | Transitive persistence with cascading

你可能已经注意到 cascade attribute有一个 CascadeType 的数组值.EJB3中的cascade 观念和Hibernate 持久化cascade 观念很相似的,但是也有一些语义上和cascadeing types 的不同 :

  • CascadeType.PERSIST: cascades the persist (create) operation to associated entities persist() is called or if the entity is managed (如果实体是受管的,当调用persist() 时,机联操作)
  • CascadeType.MERGE: cascades the merge operation to associated entities if merge() is called or if the entity is managed(如果实体是受管的,当调用merge() 时,机联操作)
  • CascadeType.REMOVE: cascades the remove operation to associated entities if delete() is called (当调用delete() 时,机联操作)
  • CascadeType.REFRESH: cascades the refresh operation to associated entities if refresh() is called (当调用refresh() 时,机联操作)
  • CascadeType.ALL: all of the above (上面所有的)

请参考 EJB3 的6.3章了解有关 cascading 和 create/merge semantics的信息.

2.2.5.5. 抓取策略 | Association fetching

你可是使用eagerly 或者lazily策略来抓取关联的实体.fetch 参数的值可以是 FetchType.LAZY 或者 FetchType.EAGER. EAGER 将会试着使用一条外连接(outer join)查询语句来得到关联的对象,然而 LAZY 是默认值,并且她将仅仅在属性第一次使用时候才出发一条查询语句. EJBQL也有一个 fetch 关键字来让你在一个特殊的查询中 override laziness . 在提高性能和is decided on a use case to use case basis方面还是很有用的.

2.2.6. 映射组合主键和外键 | Mapping composite primary and foreign keys

组合主键是用一个内嵌的类来代表的.因此你要使用 @Id@Embeddable annotations. 另外一种选择是使用 @EmbeddedId annotation. 注意: dependent class(决定主键的类) 一定要是serializable 且实现了equals()/hashCode(). 你还可以使用 @IdClassMapping identifier properties 中描述.

@Entity
public class RegionalArticle implements Serializable {
@Id
public RegionalArticlePk getPk() { ... }
}
@Embeddable(access = AccessType.FIELD)
public class RegionalArticlePk implements Serializable { ... }

or alternatively

@Entity
public class RegionalArticle implements Serializable {
@EmbeddedId
public RegionalArticlePk getPk() { ... }
}
public class RegionalArticlePk implements Serializable { ... }

@Embeddable 可以定义组件的field 或者 property access strategy(访问策略). Composite foreign keys(组合外键) (如果没有定义默认的敏感的( sensitive) 值) 利用@JoinColumns element(事实上是一个@JoinColumn的数组)来定义.显式的指定referencedColumnNames 的值被认为是一个很好的实践.然而, Hibernate 将假设 你使用和主键声明一样的顺序(you use the same order of columns as in the primary key declaration).

@Entity(access = AccessType.FIELD)
public class Parent implements Serializable {
@Id
public ParentPk id;
public int age;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumns ({
@JoinColumn(name="parentCivility", referencedColumnName = "isMale"),
@JoinColumn(name="parentLastName", referencedColumnName = "lastName"),
@JoinColumn(name="parentFirstName", referencedColumnName = "firstName")
})
public Set<Child> children; //unidirectional
...
}
@Entity(access = AccessType.FIELD)
public class Child implements Serializable {
@Id(generate = GeneratorType.AUTO)
public Integer id;
@ManyToOne
@JoinColumns ({
@JoinColumn(name="parentCivility", referencedColumnName = "isMale"),
@JoinColumn(name="parentLastName", referencedColumnName = "lastName"),
@JoinColumn(name="parentFirstName", referencedColumnName = "firstName")
})
public Parent parent; //unidirectional
}
@Embeddable(access = AccessType.FIELD)
public class ParentPk implements Serializable {
String firstName;
String lastName;
...
}

注意: referencedColumnName的使用.

2.2.7.映射第二个表 | Mapping secondary tables

利用@SecondaryTable or @SecondaryTables class level annotations,你可以映射单个实体bean(single entity bean)到几个数据表中. 为了表达属性映射到那个表中,可以使用@Column 或者@JoinColumn的secondaryTable parameter .如下所示;

@Entity
@Table(name="MainCat")
@SecondaryTables({
@SecondaryTable(name="Cat1", join={@JoinColumn(name="cat_id", referencedColumnName="id")),
@SecondaryTable(name="Cat2", uniqueConstraints={@UniqueConstraint(columnNames={"storyPart2"})})
})
public class Cat implements Serializable {
private Integer id;
private String name;
private String storyPart1;
private String storyPart2;
@Id(generate = GeneratorType.AUTO)
public Integer getId() {
return id;
}
public String getName() {
return name;
}
@Column(secondaryTable="Cat1")
public String getStoryPart1() {
return storyPart1;
}
@Column(secondaryTable="Cat2")
public String getStoryPart2() {
return storyPart2;
}

在这个例子中, nameMainCatCat表中, storyPart1在Cat1表中 并且 storyPart2 将会在 Cat2表中. 利用cat_id作为外键 Cat1 将连接到 MainCat , 而Cat2 使用 id (和 MainCat id column 的名字一样). 在storyPart2上设定了一个唯一约束.

请查看JBoss EJB 3 tutorial 或者 the Hibernate Annotations unit test suite获得更多的例子.

2.3. 映射查询 | Mapping Queries

2.3.1. 映射EJBQL/HQL查询 | Mapping EJBQL/HQL queries

你可以利用annotations来映射 EJBQL/HQL 查询. @NamedQuery@NamedQueries可以在class 或者 package level定义. 然而他们的定义是全局的 对于 session factory/entity manager factory 的范围来说. 一个命名查询用一个名字和一个查询字符串来定义.

javax.persistence.NamedQueries(
@javax.persistence.NamedQuery(name="plane.getAll", queryString="select p from Plane p")
)
package org.hibernate.test.annotations.query;
...
@Entity
@NamedQuery(name="night.moreRecentThan", queryString="select n from Night n where n.date >= :date")
public class Night {
...
}
public class MyDao {
doStuff() {
Query q = s.getNamedQuery("night.moreRecentThan");
q.setDate( "date", aMonthAgo );
List results = q.list();
...
}
...
}

2.3.2. 映射本地查询 | Mapping native queries

你可以映射一个本地查询(例如:一个普通的SQL查询).为了实现这个目标,你要利用@SqlResultSetMapping来定义SQL resultset structure. 象 @NamedQuery, 一个@SqlResultSetMapping 可以在package level 或者 class level来定义. 然而她的范围对整个应用程序来说是全局的. 就像我们所看到的,@NamedNativeQuery中一个 resultSetMapping parameter 被定义了,她代表所定义的@SqlResultSetMapping的名字.  resultset 映射声明该本地查询得到的实体.实体的每一个field被绑定到一个 SQL alias(sql别名) (或者 column name). 实体的所有fields(包括超类的) 必须出现在SQL query中. Field定义是可选择的 如果他们映射到相同的 column name 和 class property中声明的一样.

@NamedNativeQuery(name="night&area", queryString="select night.id nid, night.night_duration, "
+ " night.night_date, area.id aid, night.area_id, area.name "
+ "from Night night, Area area where night.area_id = area.id", resultSetMapping="joinMapping")
@SqlResultSetMapping(name="joinMapping", entities={
@EntityResult(name="org.hibernate.test.annotations.query.Night", fields = {
@FieldResult(name="id", column="nid"),
@FieldResult(name="duration", column="night_duration"),
@FieldResult(name="date", column="night_date"),
@FieldResult(name="area", column="area_id"),
discriminatorColumn="disc"
}),
@EntityResult(name="org.hibernate.test.annotations.query.Area", fields = {
@FieldResult(name="id", column="aid"),
@FieldResult(name="name", column="name")
})
}
)

在上面的例子中, night&area 命名映射利用了 joinMapping result set mapping(结果集映射). 该映射返回两个实体, NightArea, 每个属性被声明为列名且与列名相关联, 事实上列名根据查询得到. 让我们看看属性和列名的隐式声明.

@Entity
@SqlResultSetMapping(name="implicit", entities=@EntityResult(name="org.hibernate.test.annotations.query.SpaceShip"))
@NamedNativeQuery(name="implicitSample", queryString="select * from SpaceShip", resultSetMapping="implicit")
public class SpaceShip {
private String name;
private String model;
private double speed;
@Id(generate = GeneratorType.NONE)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="model_txt")
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
}

在上面的例子中,我们仅仅描述了result set mapping(结果集)映射的实体. property / column mappings(属性/列映射) 利用entity mapping values(实体映射值).在这种情况下 model 属性和model_txt 列相关联.

如果你利用默认映射来得到一个单实体(If you retrieve a single entity and if you use the default mapping), 你可以利用 resultClass属性来代替 resultSetMapping:

@NamedNativeQuery(name="implicitSample", queryString="select * from SpaceShip",
resultClass=SpaceShip.class)
public class SpaceShip {

2.4. Hibernate Annotation 扩展 | Hibernate Annotation Extensions

Hibernate 3.1 提供了很多附加的注释,这些注释你可以和EJB3 实体混合使用.她们被设计为EJB3注释的自然扩充(natural extension).

为了增强EJB3 的功能, hibernate提供了一些与Hibernate有关的特殊注释. org.hibernate.annotations 包包含了所有的注释.

2.4.1. Entity | 实体

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

@org.hibernate.annotations.Entity 添加了附加的元数据,当在标准@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 (允许动态SQL 插入)
  • dynamicUpdate: allow dynamic SQL for updates (允许动态SQL 更新)
  • selectBeforeUpdate: Specifies that Hibernate should never perform an SQL UPDATE unless it is certain that an object is actually modified. (指明Hibernate不可以执行一个Update Sql 除非 一个对象确定更改了)
  • 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) (乐观锁策略)

注意

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

下面是一些附加的Annotations 扩展

@org.hibernate.annotations.BatchSize (允许你定义抓取实体实例的 Batch size.当载入一个给定的实体时,Hibernate 将装载所有在持久化上下文中的相同类型的没有初始化的实体 直到Batch size) 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.Proxy (定义实体的Laziness 属性. lazy(默认值为True) 定义是否类延迟装载. proxyClassName 是用力产生代理的接口 (默认值是class自己)) 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.Where(定义一个可选的 Where Sql 子句,限制选择的类的实例) defines an optional SQL WHERE clause used when instances of this class is retrieved.

@org.hibernate.annotations.Check(在DDL 语句中定义一个可选的检查约束) defines an optional check constraints defined in the DDL statetement.

@OnDelete(action=OnDeleteAction.CASCADE) on joined subclasses:(利用一个Sql cascade 删除来代替 常规的Hibernate 机制) use a SQL cascade delete on deletion instead of the regular Hibernate mechanism.

@Table(name="tableName", indexes = { @Index(name="index1", columnNames={"column1", "column2"} ) } )(在tableName 表的 列上创建一个指定的索引. 可以用在一个primary table 或者Secondary table. @Tables 注释允许你在不同的表上应用索引. 该注释期望应用在@javax.persistence.Table or @javax.persistence.SecondaryTable(s) 出现的地方.@org.hibernate.annotations.Table 是对 @javax.persistence.Table的补充 而不是打算替换掉她.) 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

@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 { ... }
@Entity
@Inheritance(
strategy=InheritanceType.JOINED
)
public class Vegetable { ... }
@Entity
@OnDelete(action=OnDeleteAction.CASCADE)
public class Carrot extends Vegetable { ... }

2.4.2. Identifier | 标识符

@org.hibernate.annotations.GenericGenerator (允许你定义一个Hibernate 指定的Generator)allows you to define an Hibernate specific id generator.

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

strategy 是一个Hibernate3 generator strategy 的缩写 或者一个完全限定的IdentifierGenerator . 通过使用parameters attribute 你可以添加一些参数.

2.4.3. Property | 属性

2.4.3.1. Formula | 规则

有时, 你希望数据库来做一些计算,而不是在JVM中做, 你可以创建一些 virtual column. 你可以使用Sql 片断(aka formula) 来代替映射属性到列中.这种属性是只读的 (她的值是利用你的formula fragment计算出来的).

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

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

2.4.3.2. Type | 类型

@org.hibernate.annotations.Type 重写默认的 hibernate Type: 既然Hibernate 已经指出正确的类型了,这个可以是普通的而不是必须的.请参考 Hibernate reference guide 取得关于 Hibernate types的更多信息.

@org.hibernate.annotations.TypeDef and @org.hibernate.annotations.TypeDefs 允许你声明Type定义. 该注释被放在类或者包级别(class or package level). 注意:这些定义对 session factory (even at the class level) 来说是全局可用的,并且在使用以前必须先定义Type( and that type definition has to be defined before any usage).

@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() {
...
}

当使用组合用户类型(composite user type), 你不得不给出列定义.@Columns就是为了此功能而引入的.

@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;
...
}

2.4.3.3. Index | 索引

在一个列属性上利用@Index annotation 你可以定义一个Index 在一个特殊的列上,columnNames attribute将会被忽略.

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

2.4.4. Inheritance | 继承

SINGLE_TABLE 是一个很强大的策略,但是有时候, 特别是遗留系统(legacy systems), 你不能添加一个附加的辨别列(discriminator column). 为了该目的Hibernate 引入了discriminator formula 概念 :@DiscriminatorFormula 代替 @DiscriminatorColumn 并且利用一个 SQL fragment作为formula 来辨别(不再需要一个特别的列了(dedicated column) ).

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

2.4.5. Association related annotations | 与关联相关的注释

Hibernate 默认,当指定的关联元素不在数据库中时,不能确认关联,此时将抛出异常.这对于lecacy and badly maintained schemas 可能是不方便的.你可以利用@NotFound 注释来告诉Hibernate 当元素没有在数据库中时 该怎么做(例如 忽略). 该注释可以用在 @OneToOne (with FK), @ManyToOne, @OneToMany or @ManyToMany association上.

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.

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

2.4.6. Collection related annotations | 与集合相关的注释

2.4.6.1. Parameter annotations | 参数注释

设置下面的数据是可能的:

  • the batch size for collections using @BatchSize (利用@BatchSize来设置集合的batch size)
  • the where clause, using @Where (利用@Where 来指定Where子句)
  • the check clause, using @Check (利用 @Check来指定Check子句)
  • the SQL order by clause, using @OrderBy (指定SQL Order by 子句)
  • the delete cascade strategy through @OnDelete(action=OnDeleteAction.CASCADE) (指定删除机联策略)

你可以声明一个 sort comparator. 并利用@Sort annotation. 在unsorted, natural or custom comparator中指出你想使用的 comparator type. 如果你想使用你自己的comparator, 你必须利用 comparator 属性指定其实现类.

    @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.

2.4.6.2. Extra collection types | 其他的集合类型

在EJB3之外, Hibernate Annotations 还支持 true List and Array.以同样的方式映射你的集合, 并且加上@IndexColumn.该注释允许你描述建立索引的列. 你也可以在DB(表现在第一个元素上)(aka as base index)中声明索引值. 通常该值为 0 或者1.

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.

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

注意:

如果你忘记了设置 @IndexColumn, 将应用bag semantic(bag) .

Hibernate Annotations 也支持(核心类型) core types (Integer, String, Enums, ...)的集合, collections of embeddable objects(嵌入的对象集合) 和基本数据类型集合. 就像元素的集合(collection of elements).

A collection of elements(元素的集合) 利用@CollectionOfElements (as a replacement of @OneToMany)来定义collection table, @JoinTable annotation 用在association property(关联属性)上, joinColumns 定义了在实体表和集合表直接的连接列(join columns between the entity primary table and the collection table) (inverseJoincolumn 是没有用到, 应该保留为空). 对于collection of core types 或者 array of primitive types, 你可以利用 @Column在关联的属性上重写列定义. 利用@AttributeOverride你也可以重写一个collection of embeddable object列(You can also override the columns of a collection of embeddable object using @AttributeOverride).

@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(generate= GeneratorType.AUTO)
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(access = AccessType.FIELD)
public class Toy {
public String name;
public String 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;
}
}

注意:

以前的Hibernate Annotations版本中使用 @OneToMany来定义 collection of elements. 由于语义冲突, 我们引入了 @CollectionOfElements. 利用旧的方式定义collections of elements仍然没有错, 但这样是不推荐的,可能在以后的版本中不再支持.

2.4.7. Cache | 缓存

出于优化你的数据库访问,你可以激活Hibernate的second level cache.该cache 在每一个实体和集合上是可以配置的(This cache is configurable on a per entity and per collection basis).

@org.hibernate.annotations.Cache 定义缓存策略(caching strategy) 和一个给定的(given) second level cache区域. 这个注释可以用在 root entity (not the sub entities), 和集合上.

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

 

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

usage: 指定缓存并发策略(cache concurrency strategy) (NONE, READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)

(2)

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

(3)

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

2.4.8. 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.(你要先定义Filter 然后在运行的session 上使用她.)

@org.hibernate.annotations.FilterDef or @FilterDefs 利用相同的名字定义 Filter. 一个Filter定义有一个name() 和一个parameters()数组. 一个@ParamDef 有一个名字和类型. 你也可以定义一个defaultCondition() 参数, 来在一个给定的@filterDef上设置默认条件(当在@Filter中没有定义时).一个@FilterDef(s) 可以定义在类或者包级别.

@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.

我们现在需要定义一个SQL filter子句 应用于 实体装载或者集合装载. @Filter被使用, 并放在实体或者集合元素.

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

@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 { ... }

2.4.9. Queries | 查询

Hibernate 命名查询比EJB3 定义的功能要多很多,@org.hibernate.annotations.NamedQuery, @org.hibernate.annotations.NamedQueries, @org.hibernate.annotations.NamedNativeQuery and @org.hibernate.annotations.NamedNativeQueries 被引入了. 并且加入了一些属性到标准版本中,可以作为一个补充.

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:

  • 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(如果查询被缓存了,定义缓存的region)

  • fetchSize: JDBC statement fetch size for this query(用于该查询的JDBC 语句的fetch size )

  • 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.(定义注释comments )

  • 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.(是否是只读模式)

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多