乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      EJB3/JPA Annotations 學(xué)習(xí)

       昵稱5370487 2011-01-11

      使用: Hibernate ;始于: EJB; API: javax.persistence.*

      Document file and example: Hibernate, JBoss etc.

       

      一、 實體 Bean

      每個持久化POJO類都是一個實體Bean , 通過在類的定義中使用 @Entity 注解來進(jìn)行聲明。

      聲明實體Bean

      @Entity
      public class Flight implements Serializable {
        Long id;
        @Id
        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }
      }

      @Entity 注解將一個類聲明為實體 Bean, @Id 注解聲明了該實體Bean的標(biāo)識屬性。

      Hibernate 可以對類的屬性或者方法進(jìn)行注解。屬性對應(yīng)field類別,方法的 getXxx()對應(yīng)property類別。

      定義表

      通過 @Table 為實體Bean指定對應(yīng)數(shù)據(jù)庫表,目錄和schema的名字。

      @Entity
      @Table(name="tbl_sky")
      public class Sky implements Serializable {

      ...

      @Table 注解包含一個schema和一個catelog 屬性,使用@UniqueConstraints 可以定義表的唯一約束。

      @Table(name="tbl_sky",
        uniqueConstraints = {@UniqueConstraint(columnNames={"month", "day"})}
      )

      上述代碼在  "month" 和 "day" 兩個 field 上加上 unique constrainst.

      @Version 注解用于支持樂觀鎖版本控制。

      @Entity
      public class Flight implements Serializable {
         ...
         @Version
         @Column(name="OPTLOCK")
         public Integer getVersion() { ... }
      }

      version屬性映射到 "OPTLOCK" 列,entity manager 使用這個字段來檢測沖突。 一般可以用 數(shù)字 或者 timestamp 類型來支持 version.

      實體Bean中所有非static 非 transient 屬性都可以被持久化,除非用@Transient注解。

      默認(rèn)情況下,所有屬性都用 @Basic 注解。

      public transient int counter; //transient property

      private String firstname; //persistent property
      @Transient
      String getLengthInMeter() { ... } //transient property
      String getName() {... } // persistent property
      @Basic
      int getLength() { ... } // persistent property
      @Basic(fetch = FetchType.LAZY)
      String getDetailedComment() { ... } // persistent property
      @Temporal(TemporalType.TIME)
      java.util.Date getDepartureTime() { ... } // persistent property
      @Enumerated(EnumType.STRING)
      Starred getNote() { ... } //enum persisted as String in database

      上述代碼中 counter, lengthInMeter 屬性將忽略不被持久化,而 firstname, name, length 被定義為可持久化和可獲取的。

      @TemporalType.(DATE,TIME,TIMESTAMP) 分別Map java.sql.(Date, Time, Timestamp).

      @Lob 注解屬性將被持久化為 Blog 或 Clob 類型。具體的java.sql.Clob, Character[], char[] 和 java.lang.String 將被持久化為 Clob 類型. java.sql.Blob, Byte[], byte[] 和 serializable type 將被持久化為 Blob 類型。

      @Lob
      public String getFullText() {
         return fullText;  // clob type
      }


      @Lob
      public byte[] getFullCode() {
        return fullCode;  // blog type
      }

      @Column 注解將屬性映射到列。

      @Entity
      public class Flight implements Serializable {
         ...
         @Column(updatable = false, name = "flight_name", nullable = false, length=50)
         public String getName() { ... }

      定義 name 屬性映射到 flight_name column, not null, can't update, length equal 50

      @Column(
         name="columnName"; (1) 列名
         boolean unique() default false; (2)    是否在該列上設(shè)置唯一約束
         boolean nullable() default true; (3)   列可空?
         boolean insertable() default true; (4) 該列是否作為生成 insert語句的一個列
         boolean updatable() default true; (5)  該列是否作為生成 update語句的一個列
         String columnDefinition() default ""; (6)  默認(rèn)值
         String table() default ""; (7)             定義對應(yīng)的表(deault 是主表)
         int length() default 255; (8)              列長度
         int precision() default 0; // decimal precision (9)  decimal精度
         int scale() default 0; // decimal scale        (10)  decimal長度

      嵌入式對象(又稱組件)也就是別的對象定義的屬性

      組件類必須在類一級定義 @Embeddable 注解。在特定的實體關(guān)聯(lián)屬性上使用 @Embeddable 和 @AttributeOverride 注解可以覆蓋該屬性對應(yīng)的嵌入式對象的列映射。

      @Entity
      public class Person implements Serializable {
         // Persistent component using defaults
         Address homeAddress;
         @Embedded
         @AttributeOverrides( {
            @AttributeOverride(name="iso2", column = @Column(name="bornIso2") ),
            @AttributeOverride(name="name", column = @Column(name="bornCountryName") )
         } )
         Country bornIn;
         ...
      }

      @Embeddable
      public class Address implements Serializable {
         String city;
         Country nationality; //no overriding here
      }

      @Embeddable
      public class Country implements Serializable {
         private String iso2;
         @Column(name="countryName") private String name;
         public String getIso2() { return iso2; }
         public void setIso2(String iso2) { this.iso2 = iso2; }
         public String getName() { return name; }
         public void setName(String name) { this.name = name; }
         ...
      }

      Person 類定義了 Address 和  Country 對象,具體兩個類實現(xiàn)見上。

      無注解屬性默認(rèn)值:

      • 屬性為簡單類型,則映射為 @Basic

      • 屬性對應(yīng)的類型定義了 @Embeddable 注解,則映射為 @Embedded

      • 屬性對應(yīng)的類型實現(xiàn)了Serializable,則屬性被映射為@Basic并在一個列中保存該對象的serialized版本。

      • 屬性的類型為 java.sql.Clob or java.sql.Blob, 則映射到 @Lob 對應(yīng)的類型。

      映射主鍵屬性

      @Id 注解可將實體Bean中某個屬性定義為主鍵,使用@GenerateValue注解可以定義該標(biāo)識符的生成策略。

      • AUTO -  可以是 identity column, sequence 或者 table 類型,取決于不同底層的數(shù)據(jù)庫
      • TABLE - 使用table保存id值
      • IDENTITY - identity column
      • SEQUENCE - seque

      nce

      @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_STORE")
      public Integer getId() { ... }

      @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
      public Long getId() { ... }

      AUTO 生成器,適用與可移值的應(yīng)用,多個@Id可以共享同一個 identifier生成器,只要把generator屬性設(shè)成相同的值就可以。通過@SequenceGenerator 和 @TableGenerator 可以配置不同的 identifier 生成器。

      <table-generator name="EMP_GEN"
           table="GENERATOR_TABLE"
           pk-column-name="key"
           value-column-name="hi"
           pk-column-value="EMP"
           allocation-size="20"/>
      //and the annotation equivalent
      @javax.persistence.TableGenerator(
           name="EMP_GEN",
           table="GENERATOR_TABLE",
           pkColumnName = "key",
           valueColumnName = "hi"
           pkColumnValue="EMP",
           allocationSize=20
      )
      <sequence-generator name="SEQ_GEN"
           sequence-name="my_sequence"
           allocation-size="20"/>
      //and the annotation equivalent
      @javax.persistence.SequenceGenerator(
           name="SEQ_GEN",
           sequenceName="my_sequence",
           allocationSize=20
      )

       

      The next example shows the definition of a sequence generator in a class scope:

      @Entity
      @javax.persistence.SequenceGenerator(
          name="SEQ_STORE",
          sequenceName="my_sequence"
      )
      public class Store implements Serializable {
         private Long id;
         @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_STORE")
         public Long getId() { return id; }
      }

      Store類使用名為my_sequence的sequence,并且SEQ_STORE生成器對于其他類是不可見的。

      通過下面語法,你可以定義組合鍵。

      • 將組件類注解為 @Embeddable, 并將組件的屬性注解為 @Id
      • 將組件的屬性注解為 @EmbeddedId
      • 將類注解為 @IdClass,并將該實體中所有主鍵的屬性都注解為 @Id

      @Entity
      @IdClass(FootballerPk.class)
      public class Footballer {
        //part of the id key
        @Id public String getFirstname() {
          return firstname;
        }
        public void setFirstname(String firstname) {
           this.firstname = firstname;
        }
        //part of the id key
        @Id public String getLastname() {
          return lastname;
        }
        public void setLastname(String lastname) {
          this.lastname = lastname;
        }
        public String getClub() {
          return club;
        }
        public void setClub(String club) {
         this.club = club;
        }
        //appropriate equals() and hashCode() implementation
      }

      @Embeddable
      public class FootballerPk implements Serializable {
        //same name and type as in Footballer
        public String getFirstname() {
          return firstname;
        }
        public void setFirstname(String firstname) {
          this.firstname = firstname;
        }
        //same name and type as in Footballer
        public String getLastname() {
          return lastname;
        }
        public void setLastname(String lastname) {
         this.lastname = lastname;
        }
        //appropriate equals() and hashCode() implementation
      }

       

      @Entity
      @AssociationOverride( name="id.channel", joinColumns = @JoinColumn(name="chan_id") )
      public class TvMagazin {
         @EmbeddedId public TvMagazinPk id;
         @Temporal(TemporalType.TIME) Date time;
      }


      @Embeddable
      public class TvMagazinPk implements Serializable {
         @ManyToOne
         public Channel channel;
         public String name;
         @ManyToOne
         public Presenter presenter;
      }

      映射繼承關(guān)系

      EJB支持3種類型的繼承。

      • Table per Class Strategy: the <union-class> element in Hibernate 每個類一張表
      • Single Table per Class Hierarchy Strategy: the <subclass> element in Hibernate 每個類層次結(jié)構(gòu)一張表
      • Joined Subclass Strategy: the <joined-subclass> element in Hibernate 連接的子類策略

      @Inheritance 注解來定義所選的之類策略。

      每個類一張表

      @Entity
      @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
      public class Flight implements Serializable {

      有缺點,如多態(tài)查詢或關(guān)聯(lián)。Hibernate 使用 SQL Union 查詢來實現(xiàn)這種策略。 這種策略支持雙向的一對多關(guān)聯(lián),但不支持 IDENTIFY 生成器策略,因為ID必須在多個表間共享。一旦使用就不能使用AUTO和IDENTIFY生成器。

      每個類層次結(jié)構(gòu)一張表

      @Entity
      @Inheritance(strategy=InheritanceType.SINGLE_TABLE )
      @DiscriminatorColumn(
          name="planetype",
          discriminatorType=DiscriminatorType.STRING
      )
      @DiscriminatorValue("Plane")
      public class Plane { ... }

      @Entity
      @DiscriminatorValue("A320")
      public class A320 extends Plane { ... }

      整個層次結(jié)構(gòu)中的所有父類和子類屬性都映射到同一個表中,他們的實例通過一個辨別符列(discriminator)來區(qū)分。

      Plane 是父類。@DiscriminatorColumn 注解定義了辨別符列。對于繼承層次結(jié)構(gòu)中的每個類, @DiscriminatorValue 注解指定了用來辨別該類的值。 辨別符列名字默認(rèn)為 DTYPE,其默認(rèn)值為實體名。其類型為DiscriminatorType.STRING。

      連接的子類

      @Entity
      @Inheritance(strategy=InheritanceType.JOINED )
      public class Boat implements Serializable { ... }


      @Entity
      public class Ferry extends Boat { ... }

      @Entity
      @PrimaryKeyJoinColumn(name="BOAT_ID")
      public class AmericaCupClass extends Boat { ... }

      以上所有實體使用 JOINED 策略 Ferry和Boat class使用同名的主鍵關(guān)聯(lián)(eg: Boat.id = Ferry.id), AmericaCupClass 和 Boat 關(guān)聯(lián)的條件為 Boat.id = AmericaCupClass.BOAT_ID.

      從父類繼承的屬性

      @MappedSuperclass
      public class BaseEntity {
        @Basic
        @Temporal(TemporalType.TIMESTAMP)
        public Date getLastUpdate() { ... }
        public String getLastUpdater() { ... }
        ...
      }


      @Entity class Order extends BaseEntity {
        @Id public Integer getId() { ... }
        ...
      }

      繼承父類的一些屬性,但不用父類作為映射實體,這時候需要 @MappedSuperclass 注解。 上述實體映射到數(shù)據(jù)庫中的時候?qū)?yīng) Order 實體Bean, 其具有 id, lastUpdate, lastUpdater 三個屬性。如果沒有@MappedSuperclass 注解,則父類中屬性忽略,這是 Order 實體 Bean 只有 id 一個屬性。

      映射實體Bean的關(guān)聯(lián)關(guān)系

      一對一

      使用 @OneToOne 注解可以建立實體Bean之間的一對一關(guān)系。一對一關(guān)系有3種情況。

      • 關(guān)聯(lián)的實體都共享同樣的主鍵。

      @Entity
      public class Body {
        @Id
        public Long getId() { return id; }
        @OneToOne(cascade = CascadeType.ALL)
        @PrimaryKeyJoinColumn
        public Heart getHeart() {
           return heart;
        }
        ...
      }

      @Entity
      public class Heart {
        @Id
        public Long getId() { ...}
      }

      通過@PrimaryKeyJoinColumn 注解定義了一對一的關(guān)聯(lián)關(guān)系。


      • 其中一個實體通過外鍵關(guān)聯(lián)到另一個實體的主鍵。注:一對一,則外鍵必須為唯一約束。

      @Entity
      public class Customer implements Serializable {
         @OneToOne(cascade = CascadeType.ALL)
         @JoinColumn(name="passport_fk")
         public Passport getPassport() {
         ...
      }


      @Entity
      public class Passport implements Serializable {
         @OneToOne(mappedBy = "passport")
         public Customer getOwner() {
         ...
      }

      通過@JoinColumn 注解定義一對一的關(guān)聯(lián)關(guān)系。如果沒有@JoinColumn注解,則系統(tǒng)自動處理,在主表中將創(chuàng)建連接列,列名為:主題的關(guān)聯(lián)屬性名 + 下劃線 + 被關(guān)聯(lián)端的主鍵列名。上例為 passport_id, 因為Customer 中關(guān)聯(lián)屬性為 passport, Passport 的主鍵為 id.


      • 通過關(guān)聯(lián)表來保存兩個實體之間的關(guān)聯(lián)關(guān)系。注:一對一,則關(guān)聯(lián)表每個外鍵都必須是唯一約束。

      @Entity
      public class Customer implements Serializable {
         @OneToOne(cascade = CascadeType.ALL)
         @JoinTable (name = "CustomerPassports",
              joinColumns = @JoinColumn(name="customer_fk"),
              inverseJoinColumns = @JoinColumn(name="passport_fk")
         )
         public Passport getPassport() {
         ...
      }


      @Entity public class Passport implements Serializable {
         @OneToOne(mappedBy = "passport")
         public Customer getOwner() {
         ...
      }

      Customer 通過 CustomerPassports 關(guān)聯(lián)表和 Passport 關(guān)聯(lián)。該關(guān)聯(lián)表通過 passport_fk 外鍵指向 Passport 表,該信心定義為 inverseJoinColumns 的屬性值。 通過 customer_fk 外鍵指向 Customer 表,該信息定義為 joinColumns 屬性值。

       

      多對一

      使用 @ManyToOne 注解定義多對一關(guān)系。

      @Entity()
      public class Flight implements Serializable {
        @ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
        @JoinColumn(name="COMP_ID")
        public Company getCompany() {
          return company;
        }
        ...
      }

      其中@JoinColumn 注解是可選的,關(guān)鍵字段默認(rèn)值和一對一關(guān)聯(lián)的情況相似。列名為:主題的關(guān)聯(lián)屬性名 + 下劃線 + 被關(guān)聯(lián)端的主鍵列名。本例中為company_id,因為關(guān)聯(lián)的屬性是company, Company的主鍵為 id.

      @ManyToOne 注解有個targetEntity屬性,該參數(shù)定義了目標(biāo)實體名。通常不需要定義,大部分情況為默認(rèn)值。但下面這種情況則需要 targetEntity 定義使用接口作為返回值,而不是常用的實體 )。

      @Entity()
      public class Flight implements Serializable {
         @ManyToOne(cascade=   {CascadeType.PERSIST,CascadeType.MERGE},targetEntity= CompanyImpl.class)
         @JoinColumn(name="COMP_ID")
         public Company getCompany() {
           return company;
         }
         ...
      }


      public interface Company {
         ...

      多對一也可以通過關(guān)聯(lián)表的方式來映射,通過 @JoinTable 注解可定義關(guān)聯(lián)表。該關(guān)聯(lián)表包含指回實體 的外鍵(通過@JoinTable.joinColumns )以及指向目標(biāo)實體表 的外鍵(通過@JoinTable.inverseJoinColumns ).

      @Entity()
      public class Flight implements Serializable {

         @ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
         @JoinTable(name="Flight_Company",
             joinColumns = @JoinColumn(name="FLIGHT_ID"),
             inverseJoinColumns = @JoinColumn(name="COMP_ID")
         )
         public Company getCompany() {
             return company;
         }
         ...
      }

      集合類型

       一對多

      @OneToMany 注解可定義一對多關(guān)聯(lián)。一對多關(guān)聯(lián)可以是雙向的。

      雙向

      規(guī)范中多對一端幾乎總是雙向關(guān)聯(lián)中的主體(owner)端,而一對多的關(guān)聯(lián)注解為 @OneToMany(mappedBy=)

      @Entity
      public class Troop {
        @OneToMany(mappedBy="troop")
        public Set<Soldier> getSoldiers() {
        ...
      }


      @Entity
      public class Soldier {
        @ManyToOne
        @JoinColumn(name="troop_fk")
        public Troop getTroop() {
        ...
        }

      Troop 通過troop屬性和Soldier建立了一對多的雙向關(guān)聯(lián)。在 mappedBy 端不必也不能定義任何物理映射。

      單向

      @Entity
      public class Customer implements Serializable {
         @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
         @JoinColumn(name="CUST_ID")
         public Set<Ticket> getTickets() {
            ...
         }

      @Entity
      public class Ticket implements Serializable {
         ... //no bidir
      }

      一般通過連接表來實現(xiàn)這種關(guān)聯(lián),可以通過@JoinColumn 注解來描述這種單向關(guān)聯(lián)關(guān)系。上例 Customer 通過 CUST_ID 列和 Ticket 建立了單向關(guān)聯(lián)關(guān)系。

      通過關(guān)聯(lián)表來處理單向關(guān)聯(lián)

      @Entity
      public class Trainer {
        @OneToMany
        @JoinTable(
           name="TrainedMonkeys",
           joinColumns = @JoinColumn( name="trainer_id"),
           inverseJoinColumns = @JoinColumn( name="monkey_id")
        )
        public Set<Monkey> getTrainedMonkeys() {
           ...
        }


      @Entity
      public class Monkey {
        ... //no bidir
      }

      通過關(guān)聯(lián)表來處理單向一對多關(guān)系是首選,這種關(guān)聯(lián)通過 @JoinTable 注解來進(jìn)行描述。上例子中 Trainer 通過TrainedMonkeys表和Monkey建立了單向關(guān)聯(lián)關(guān)系。其中外鍵trainer_id關(guān)聯(lián)到Trainer(joinColumns)而外鍵monkey_id關(guān)聯(lián)到Monkey(inverseJoinColumns).

      默認(rèn)處理機制

      通過連接表來建立單向一對多關(guān)聯(lián)不需要描述任何物理映射,表名由一下3個部分組成,主表(owner table)表名 + 下劃線 + 從表(the other side table)表名指向主表的外鍵名:主表表名+下劃線+主表主鍵列名 指向從表的外鍵定義為唯一約束,用來表示一對多的關(guān)聯(lián)關(guān)系 。

      @Entity
      public class Trainer {
        @OneToMany
        public Set<Tiger> getTrainedTigers () {
        ...
      }


      @Entity
      public class Tiger {
        ... //no bidir
      }

      上述例子中 Trainer 和 Tiger 通過 Trainer_Tiger 連接表建立單向關(guān)聯(lián)關(guān)系。其中外鍵 trainer_id 關(guān)聯(lián)到 Trainer表,而外鍵 trainedTigers _id 關(guān)聯(lián)到 Tiger 表。

      多對多

      通過 @ManyToMany 注解定義多對多關(guān)系,同時通過 @JoinTable 注解描述關(guān)聯(lián)表和關(guān)聯(lián)條件。其中一端定義為 owner, 另一段定義為 inverse(對關(guān)聯(lián)表進(jìn)行更新操作,這段被忽略)。

      @Entity
      public class Employer implements Serializable {
        @ManyToMany(
          targetEntity=org.hibernate.test.metadata.manytomany.Employee.class,
          cascade={CascadeType.PERSIST, CascadeType.MERGE}
        )
        @JoinTable(
          name="EMPLOYER_EMPLOYEE",
          joinColumns=@JoinColumn(name="EMPER_ID"),
          inverseJoinColumns=@JoinColumn(name="EMPEE_ID")
        )
        public Collection getEmployees() {
          return employees;
        }
        ...
      }

      @Entity
      public class Employee implements Serializable {
        @ManyToMany(
          cascade = {CascadeType.PERSIST, CascadeType.MERGE},
          mappedBy = "employees",
          targetEntity = Employer.class
        )
        public Collection getEmployers() {
          return employers;
        }
      }

      默認(rèn)值:

      關(guān)聯(lián)表名:主表表名 + 下劃線 + 從表表名;關(guān)聯(lián)表到主表的外鍵:主表表名 + 下劃線 + 主表中主鍵列名;關(guān)聯(lián)表到從表的外鍵名:主表中用于關(guān)聯(lián)的屬性名 + 下劃線 + 從表的主鍵列名。

      用 cascading 實現(xiàn)傳播持久化(Transitive persistence)

      cascade 屬性接受值為 CascadeType 數(shù)組,其類型如下:

      CascadeType.PERSIST : cascades the persist (create) operation to associated entities persist() is called or if the entity is managed 如果一個實體是受管狀態(tài),或者當(dāng) persist() 函數(shù)被調(diào)用時,觸發(fā)級聯(lián)創(chuàng)建(create)操作 。


      CascadeType.MERGE : cascades the merge operation to associated entities if merge() is called or if the entity is managed 如果一個實體是受管狀態(tài),或者當(dāng) merge() 函數(shù)被調(diào)用時,觸發(fā)級聯(lián)合并(merge)操作 。


      CascadeType.REMOVE : cascades the remove operation to associated entities if delete() is called 當(dāng) delete() 函數(shù)被調(diào)用時,觸發(fā)級聯(lián)刪除(remove)操作 。


      CascadeType.REFRESH : cascades the refresh operation to associated entities if refresh() is called  當(dāng) refresh() 函數(shù)被調(diào)用時,出發(fā)級聯(lián)更新(refresh)操作 。


      CascadeType.ALL : all of the above  以上全部

      映射二級列表

      使用類一級的 @SecondaryTable 和 @SecondaryTables 注解可以實現(xiàn)單個實體到多個表的映射。使用 @Column 或者 @JoinColumn 注解中的 table 參數(shù)可以指定某個列所屬的特定表。

      @Entity
      @Table(name="MainCat ")
      @SecondaryTables({
          @SecondaryTable(name="Cat1", pkJoinColumns={
                 @PrimaryKeyJoinColumn(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 @GeneratedValue
        public Integer getId() {
          return id;
        }
        public String getName() {
          return name;
        }
        @Column(table="Cat1")
        public String getStoryPart1() {
          return storyPart1;
        }
        @Column(table="Cat2")
        public String getStoryPart2() {
          return storyPart2;
        }

      上述例子中, name 保存在 MainCat 表中,storyPart1保存在 Cat1 表中,storyPart2 保存在 Cat2 表中。 Cat1 表通過外鍵 cat_id 和 MainCat 表關(guān)聯(lián), Cat2 表通過 id 列和 MainCat 表關(guān)聯(lián)。對storyPart2 列還定義了唯一約束。

      映射查詢

      使用注解可以映射 EJBQL/HQL 查詢,@NamedQuery 和 @NamedQueries 是可以使用在類級別或者JPA的XML文件中的注解。

      <entity-mappings>
       <named-query name="plane.getAll">
        <query>select p from Plane p</query>
       </named-query>
       ...
      </entity-mappings>
      ...
      @Entity
      @NamedQuery(name="night.moreRecentThan", query="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();
         ...
       }
       ...
      }

      可以通過定義 QueryHint 數(shù)組的 hints 屬性為查詢提供一些 hint 信息。下圖是一些 Hibernate hints:

       

      映射本地化查詢

      通過@SqlResultSetMapping 注解來描述 SQL 的 resultset 結(jié)構(gòu)。如果定義多個結(jié)果集映射,則用 @SqlResultSetMappings。

      @NamedNativeQuery(name="night&area", query="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(entityClass=org.hibernate.test.annotations.query.Night.class, 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(entityClass=org.hibernate.test.annotations.query.Area.class, fields = {
         @FieldResult(name="id", column="aid"),
         @FieldResult(name="name", column="name")
        })
       }
      )

      上面的例子,名為“night&area”的查詢和 "joinMapping"結(jié)果集映射對應(yīng),該映射返回兩個實體,分別為 Night 和 Area, 其中每個屬性都和一個列關(guān)聯(lián),列名通過查詢獲取。

      @Entity
      @SqlResultSetMapping(name="implicit",
        entities=@EntityResult(
          entityClass=org.hibernate.test.annotations.@NamedNativeQuery(
            name="implicitSample", query="select * from SpaceShip",
            resultSetMapping="implicit")
      public class SpaceShip {
       private String name;
       private String model;
       private double speed;
       @Id
       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;
       }
      }

      上例中 model1 屬性綁定到 model_txt 列,如果和相關(guān)實體關(guān)聯(lián)設(shè)計到組合主鍵,那么應(yīng)該使用 @FieldResult 注解來定義每個外鍵列。@FieldResult的名字組成:定義這種關(guān)系的屬性名字 + "." + 主鍵名或主鍵列或主鍵屬性。

      @Entity
      @SqlResultSetMapping(name="compositekey",
       entities=@EntityResult(entityClass=org.hibernate.test.annotations.query.SpaceShip.class,
        fields = {
         @FieldResult(name="name", column = "name"),
         @FieldResult(name="model", column = "model"),
         @FieldResult(name="speed", column = "speed"),
         @FieldResult(name="captain.firstname", column = "firstn"),
         @FieldResult(name="captain.lastname", column = "lastn"),

         @FieldResult(name="dimensions.length", column = "length"),
         @FieldResult(name="dimensions.width", column = "width")
        }),
       columns = { @ColumnResult(name = "surface"),
       
      @ColumnResult(name = "volume") } )
       @NamedNativeQuery(name="compositekey",
       query="select name, model, speed, lname as lastn, fname as firstn, length, width, length * width as resultSetMapping="compositekey")
      })

      如果查詢返回的是單個實體,或者打算用系統(tǒng)默認(rèn)的映射,這種情況下可以不使用 resultSetMapping,而使用resultClass屬性,例如:

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

      Hibernate 獨有的注解擴展

      Hibernate 提供了與其自身特性想吻合的注解,org.hibernate.annotations package包含了這些注解。

      實體

      org.hibernate.annotations.Entity 定義了  Hibernate 實體需要的信息。

      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從不運行SQL Update,除非能確定對象已經(jīng)被修改

       


      polymorphism : whether the entity polymorphism is of PolymorphismType.IMPLICIT (default) or PolymorphismType.EXPLICIT 指出實體多態(tài)是 PolymorphismType.IMPLICIT(默認(rèn))還是PolymorphismType.EXPLICIT


      optimisticLock : optimistic locking strategy (OptimisticLockType.VERSION, OptimisticLockType.NONE, OptimisticLockType.DIRTY or OptimisticLockType.ALL) 樂觀鎖策略

      標(biāo)識符

      @org.hibernate.annotations.GenericGenerator和@org.hibernate.annotations.GenericGenerators允許你定義hibernate特有的標(biāo)識符。

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

      新例子

      @GenericGenerators(
       {
        @GenericGenerator(
         name="hibseq",
         strategy = "seqhilo",
         parameters = {
          @Parameter(name="max_lo", value = "5"),
          @Parameter(name="sequence", value="heybabyhey")
         }
        ),
        @GenericGenerator(...)
       }
      )

      自然ID

      @NaturalId 注解標(biāo)識

      公式

      讓數(shù)據(jù)庫而不是JVM進(jìn)行計算。

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

      索引

      通過在列屬性(property)上使用@Index注解,可以指定特定列的索引,columnNames屬性(attribute)將隨之被忽略。

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

      辨別符

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

      過濾 查詢 ...

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

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多