小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

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. 機聯(lián)持久化 | Transitive persistence with cascading

你可能已經(jīng)注意到 cascade attribute有一個 CascadeType 的數(shù)組值.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 (如果實體是受管的,當調(diào)用persist() 時,機聯(lián)操作)
  • CascadeType.MERGE: cascades the merge operation to associated entities if merge() is called or if the entity is managed(如果實體是受管的,當調(diào)用merge() 時,機聯(lián)操作)
  • CascadeType.REMOVE: cascades the remove operation to associated entities if delete() is called (當調(diào)用delete() 時,機聯(lián)操作)
  • CascadeType.REFRESH: cascades the refresh operation to associated entities if refresh() is called (當調(diào)用refresh() 時,機聯(lián)操作)
  • CascadeType.ALL: all of the above (上面所有的)

請參考 EJB3 的6.3章了解有關 cascading 和 create/merge semantics的信息.

2.2.5.5. 抓取策略 | Association fetching

你可是使用eagerly 或者lazily策略來抓取關聯(lián)的實體.fetch 參數(shù)的值可以是 FetchType.LAZY 或者 FetchType.EAGER. EAGER 將會試著使用一條外連接(outer join)查詢語句來得到關聯(lián)的對象,然而 LAZY 是默認值,并且她將僅僅在屬性第一次使用時候才出發(fā)一條查詢語句. EJBQL也有一個 fetch 關鍵字來讓你在一個特殊的查詢中 override laziness . 在提高性能和is decided on a use case to use case basis方面還是很有用的.

2.2.6. 映射組合主鍵和外鍵 | Mapping composite primary and foreign keys

組合主鍵是用一個內(nèi)嵌的類來代表的.因此你要使用 @Id@Embeddable annotations. 另外一種選擇是使用 @EmbeddedId annotation. 注意: dependent class(決定主鍵的類) 一定要是serializable 且實現(xiàn)了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的數(shù)組)來定義.顯式的指定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)到幾個數(shù)據(jù)表中. 為了表達屬性映射到那個表中,可以使用@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查詢).為了實現(xiàn)這個目標,你要利用@SqlResultSetMapping來定義SQL resultset structure. 象 @NamedQuery, 一個@SqlResultSetMapping 可以在package level 或者 class level來定義. 然而她的范圍對整個應用程序來說是全局的. 就像我們所看到的,@NamedNativeQuery中一個 resultSetMapping parameter 被定義了,她代表所定義的@SqlResultSetMapping的名字.  resultset 映射聲明該本地查詢得到的實體.實體的每一個field被綁定到一個 SQL alias(sql別名) (或者 column name). 實體的所有fields(包括超類的) 必須出現(xiàn)在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, 每個屬性被聲明為列名且與列名相關聯(lián), 事實上列名根據(jù)查詢得到. 讓我們看看屬性和列名的隱式聲明.

@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 列相關聯(lián).

如果你利用默認映射來得到一個單實體(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 添加了附加的元數(shù)據(jù),當在標準@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 (允許動態(tài)SQL 插入)
  • dynamicUpdate: allow dynamic SQL for updates (允許動態(tài)SQL 更新)
  • selectBeforeUpdate: Specifies that Hibernate should never perform an SQL UPDATE unless it is certain that an object is actually modified. (指明Hibernate不可以執(zhí)行一個Update Sql 除非 一個對象確定更改了)
  • polymorphism: whether the entity polymorphism is of PolymorphismType.IMPLICIT (default) or PolymorphismType.EXPLICIT
  • persister: allow the overriding of the default persister implementation (聲明顯式和隱式多態(tài))
  • 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 是用力產(chǎn)生代理的接口 (默認值是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 刪除來代替 常規(guī)的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 表的 列上創(chuàng)建一個指定的索引. 可以用在一個primary table 或者Secondary table. @Tables 注釋允許你在不同的表上應用索引. 該注釋期望應用在@javax.persistence.Table or @javax.persistence.SecondaryTable(s) 出現(xiàn)的地方.@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 你可以添加一些參數(shù).

2.4.3. Property | 屬性

2.4.3.1. Formula | 規(guī)則

有時, 你希望數(shù)據(jù)庫來做一些計算,而不是在JVM中做, 你可以創(chuàng)建一些 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 已經(jīng)指出正確的類型了,這個可以是普通的而不是必須的.請參考 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 是一個很強大的策略,但是有時候, 特別是遺留系統(tǒng)(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 | 與關聯(lián)相關的注釋

Hibernate 默認,當指定的關聯(lián)元素不在數(shù)據(jù)庫中時,不能確認關聯(lián),此時將拋出異常.這對于lecacy and badly maintained schemas 可能是不方便的.你可以利用@NotFound 注釋來告訴Hibernate 當元素沒有在數(shù)據(jù)庫中時 該怎么做(例如 忽略). 該注釋可以用在 @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 | 參數(shù)注釋

設置下面的數(shù)據(jù)是可能的:

  • 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) (指定刪除機聯(lián)策略)

你可以聲明一個 sort comparator. 并利用@Sort annotation. 在unsorted, natural or custom comparator中指出你想使用的 comparator type. 如果你想使用你自己的comparator, 你必須利用 comparator 屬性指定其實現(xiàn)類.

    @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(表現(xiàn)在第一個元素上)(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(嵌入的對象集合) 和基本數(shù)據(jù)類型集合. 就像元素的集合(collection of elements).

A collection of elements(元素的集合) 利用@CollectionOfElements (as a replacement of @OneToMany)來定義collection table, @JoinTable annotation 用在association property(關聯(lián)屬性)上, joinColumns 定義了在實體表和集合表直接的連接列(join columns between the entity primary table and the collection table) (inverseJoincolumn 是沒有用到, 應該保留為空). 對于collection of core types 或者 array of primitive types, 你可以利用 @Column在關聯(lián)的屬性上重寫列定義. 利用@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 | 緩存

出于優(yōu)化你的數(shù)據(jù)庫訪問,你可以激活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區(qū)域. 這個注釋可以用在 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: 指定緩存并發(fā)策略(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()數(shù)組. 一個@ParamDef 有一個名字和類型. 你也可以定義一個defaultCondition() 參數(shù), 來在一個給定的@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.

我們現(xiàn)在需要定義一個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.(是否是只讀模式)

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多