Hibernate.orgCommunity Documentation

第5章 基本的な O/R マッピング

5.1. マッピング定義
5.1.1. Entity
5.1.2. Identifiers
5.1.3. Optimistic locking properties (optional)
5.1.4. property
5.1.5. Embedded objects (aka components)
5.1.6. Inheritance strategy
5.1.7. Mapping one to one and one to many associations
5.1.8. natural-id
5.1.9. Any
5.1.10. プロパティ
5.1.11. Some hbm.xml specificities
5.2. Hibernate の型
5.2.1. エンティティと値
5.2.2. 基本的な型
5.2.3. カスタム型
5.3. 1つのクラスに1つ以上のマッピング
5.4. バッククォートで囲んだ SQL 識別子
5.5. 生成プロパティ
5.6. Column transformers: read and write expressions
5.7. 補助的なデータベースオブジェクト

Object/relational mappings can be defined in three approaches:

Annotations are split in two categories, the logical mapping annotations (describing the object model, the association between two entities etc.) and the physical mapping annotations (describing the physical schema, tables, columns, indexes, etc). We will mix annotations from both categories in the following code examples.

JPA annotations are in the javax.persistence.* package. Hibernate specific extensions are in org.hibernate.annotations.*. You favorite IDE can auto-complete annotations and their attributes for you (even without a specific "JPA" plugin, since JPA annotations are plain Java 5 annotations).

Here is an example of mapping

package eg;


@Entity 
@Table(name="cats") @Inheritance(strategy=SINGLE_TABLE)
@DiscriminatorValue("C") @DiscriminatorColumn(name="subclass", discriminatorType=CHAR)
public class Cat {
   
   @Id @GeneratedValue
   public Integer getId() { return id; }
   public void setId(Integer id) { this.id = id; }
   private Integer id;
   public BigDecimal getWeight() { return weight; }
   public void setWeight(BigDecimal weight) { this.weight = weight; }
   private BigDecimal weight;
   @Temporal(DATE) @NotNull @Column(updatable=false)
   public Date getBirthdate() { return birthdate; }
   public void setBirthdate(Date birthdate) { this.birthdate = birthdate; }
   private Date birthdate;
   @org.hibernate.annotations.Type(type="eg.types.ColorUserType")
   @NotNull @Column(updatable=false)
   public ColorType getColor() { return color; }
   public void setColor(ColorType color) { this.color = color; }
   private ColorType color;
   @NotNull @Column(updatable=false)
   public String getSex() { return sex; }
   public void setSex(String sex) { this.sex = sex; }
   private String sex;
   @NotNull @Column(updatable=false)
   public Integer getLitterId() { return litterId; }
   public void setLitterId(Integer litterId) { this.litterId = litterId; }
   private Integer litterId;
   @ManyToOne @JoinColumn(name="mother_id", updatable=false)
   public Cat getMother() { return mother; }
   public void setMother(Cat mother) { this.mother = mother; }
   private Cat mother;
   @OneToMany(mappedBy="mother") @OrderBy("litterId")
   public Set<Cat> getKittens() { return kittens; }
   public void setKittens(Set<Cat> kittens) { this.kittens = kittens; }
   private Set<Cat> kittens = new HashSet<Cat>();
}
@Entity @DiscriminatorValue("D")
public class DomesticCat extends Cat {
   public String getName() { return name; }
   public void setName(String name) { this.name = name }
   private String name;
}
@Entity
public class Dog { ... }

The legacy hbm.xml approach uses an XML schema designed to be readable and hand-editable. The mapping language is Java-centric, meaning that mappings are constructed around persistent class declarations and not table declarations.

多くの Hibernate ユーザーは XML マッピングの記述を手作業で行いますが、 XDoclet, Middlegen, AndroMDA というようなマッピングドキュメントを生成するツールがいくつか存在することを覚えておいてください。

サンプルのマッピングから始めましょう:


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="eg">

        <class name="Cat"
            table="cats"
            discriminator-value="C">

                <id name="id">
                        <generator class="native"/>
                </id>

                <discriminator column="subclass"
                     type="character"/>

                <property name="weight"/>

                <property name="birthdate"
                    type="date"
                    not-null="true"
                    update="false"/>

                <property name="color"
                    type="eg.types.ColorUserType"
                    not-null="true"
                    update="false"/>

                <property name="sex"
                    not-null="true"
                    update="false"/>

                <property name="litterId"
                    column="litterId"
                    update="false"/>

                <many-to-one name="mother"
                    column="mother_id"
                    update="false"/>

                <set name="kittens"
                    inverse="true"
                    order-by="litter_id">
                        <key column="mother_id"/>
                        <one-to-many class="Cat"/>
                </set>

                <subclass name="DomesticCat"
                    discriminator-value="D">

                        <property name="name"
                            type="string"/>

                </subclass>

        </class>

        <class name="Dog">
                <!-- mapping for Dog could go here -->
        </class>

</hibernate-mapping>

We will now discuss the concepts of the mapping documents (both annotations and XML). We will only describe, however, the document elements and attributes that are used by Hibernate at runtime. The mapping document also contains some extra optional attributes and elements that affect the database schemas exported by the schema export tool (for example, the not-null attribute).

An entity is a regular Java object (aka POJO) which will be persisted by Hibernate.

To mark an object as an entity in annotations, use the @Entity annotation.

@Entity

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

That's pretty much it, the rest is optional. There are however any options to tweak your entity mapping, let's explore them.

@Table lets you define the table the entity will be persisted into. If undefined, the table name is the unqualified class name of the entity. You can also optionally define the catalog, the schema as well as unique constraints on the table.

@Entity

@Table(name="TBL_FLIGHT", 
       schema="AIR_COMMAND", 
       uniqueConstraints=
           @UniqueConstraint(
               name="flight_number", 
               columnNames={"comp_prefix", "flight_number"} ) )
public class Flight implements Serializable {
    @Column(name="comp_prefix")
    public String getCompagnyPrefix() { return companyPrefix; }
    @Column(name="flight_number")
    public String getNumber() { return number; }
}

The constraint name is optional (generated if left undefined). The column names composing the constraint correspond to the column names as defined before the Hibernate NamingStrategy is applied.

@Entity.name lets you define the shortcut name of the entity you can used in JP-QL and HQL queries. It defaults to the unqualified class name of the class.

Hibernate goes beyond the JPA specification and provide additional configurations. Some of them are hosted on @org.hibernate.annotations.Entity:

Some entities are not mutable. They cannot be updated or deleted by the application. This allows Hibernate to make some minor performance optimizations.. Use the @Immutable annotation.

You can also alter how Hibernate deals with lazy initialization for this class. On @Proxy, use lazy=false to disable lazy fetching (not recommended). You can also specify an interface to use for lazy initializing proxies (defaults to the class itself): use proxyClass on @Proxy. Hibernate will initially return proxies (Javassist or CGLIB) that implement the named interface. The persistent object will load when a method of the proxy is invoked. See "Initializing collections and proxies" below.

@BatchSize specifies a "batch size" for fetching instances of this class by identifier. Not yet loaded instances are loaded batch-size at a time (default 1).

You can specific an arbitrary SQL WHERE condition to be used when retrieving objects of this class. Use @Where for that.

In the same vein, @Check lets you define an SQL expression used to generate a multi-row check constraint for automatic schema generation.

There is no difference between a view and a base table for a Hibernate mapping. This is transparent at the database level, although some DBMS do not support views properly, especially with updates. Sometimes you want to use a view, but you cannot create one in the database (i.e. with a legacy schema). In this case, you can map an immutable and read-only entity to a given SQL subselect expression using @org.hibernate.annotations.Subselect:

@Entity

@Subselect("select item.name, max(bid.amount), count(*) "
        + "from item "
        + "join bid on bid.item_id = item.id "
        + "group by item.name")
@Synchronize( {"item", "bid"} ) //tables impacted
public class Summary {
    @Id
    public String getId() { return id; }
    ...
}

テーブルをこのエンティティと同期するように定義してください。オートフラッシュが確実に起こるように、また導出エンティティに対するクエリが古いデータを返さないようにするためです。 <subselect> は属性とネストしたマッピング属性のどちらでも利用できます。

We will now explore the same options using the hbm.xml structure. You can declare a persistent class using the class element. For example:

<class
        name="(1)ClassName"
        table=(2)"tableName"
        discri(3)minator-value="discriminator_value"
        mutabl(4)e="true|false"
        schema(5)="owner"
        catalo(6)g="catalog"
        proxy=(7)"ProxyInterface"
        dynami(8)c-update="true|false"
        dynami(9)c-insert="true|false"
        select(10)-before-update="true|false"
        polymo(11)rphism="implicit|explicit"
        where=(12)"arbitrary sql where condition"
        persis(13)ter="PersisterClass"
        batch-(14)size="N"
        optimi(15)stic-lock="none|version|dirty|all"
        lazy="(16)true|false"
        entity(17)-name="EntityName"
        check=(18)"arbitrary sql check condition"
        rowid=(19)"rowid"
        subsel(20)ect="SQL expression"
        abstra(21)ct="true|false"
        node="element-name"
/>

1

name (オプション):永続クラス(またはインターフェース)の完全修飾 Java クラス名。もしこの属性が欠落している場合、 POJO ではないエンティティに対するマッピングとして扱われます。

2

table (オプション - デフォルトは修飾されていないクラス名):データベーステーブルの名前。

3

discriminator-value (オプション - デフォルトはクラス名): ポリモーフィックな振る舞いに使われる個々のサブクラスを識別するための値。値は nullnot null のいずれかを取ります。

4

mutable (オプション、デフォルトは true ): そのクラスのインスタンスが更新可能(または不可能)であることを指定します。

5

schema (オプション): ルートの <hibernate-mapping> 要素で指定したスキーマ名をオーバーライドします。

6

catalog (オプション): ルートの <hibernate-mapping> 要素で指定したカタログ名をオーバーライドします。

7

proxy (オプション):遅延初期化プロキシに使うインターフェースを指定します。永続化するクラス名そのものを指定することも可能です。

8

dynamic-update (オプション、 デフォルトは false ):値が変更されたカラムだけを含む SQL の UPDATE 文を、実行時に生成することを指定します。

9

dynamic-insert (オプション, デフォルトは false ):値が null ではないカラムだけを含む SQL の INSERT 文を、実行時に生成することを指定します。

10

select-before-update (オプション、デフォルトは false): オブジェクトが変更されたのが確実でないならば、 Hibernate が SQL の UPDATE決して実行しない ことを指定します。ある特定の場合(実際的には、一時オブジェクトが update() を使い、新しいセッションと関連付けられた時だけ)、 UPDATE が実際に必要かどうかを決定するために、 Hibernate が余分な SQL の SELECT 文を実行することを意味します。

11

polymorphisms (optional - defaults to implicit): determines whether implicit or explicit query polymorphisms is used.

12

where (オプション): このクラスのオブジェクトを検索するときに使用する、任意の SQL の WHERE 条件を指定します。

13

persister (オプション):カスタム ClassPersister を指定します。

14

batch-size (オプション、デフォルトは 1 ): 識別子でこのクラスのインスタンスを復元するときの「バッチサイズ」を指定します。

15

optimistic-lock (オプション、デフォルトは version ): 楽観ロック戦略を決定します。

(16)

lazy (オプション): lazy="false" と設定することで、遅延フェッチができなくなります。

(17)

entity-name (optional - defaults to the class name): Hibernate3 allows a class to be mapped multiple times, potentially to different tables. It also allows entity mappings that are represented by Maps or XML at the Java level. In these cases, you should provide an explicit arbitrary name for the entity. See 「動的モデル」 and 20章XML マッピング for more information.

(18)

check (オプション):自動的にスキーマを生成するために、複数行の check 制約を生成する SQL 式。

(19)

rowid (オプション): Hibernate は、それをサポートしているデータベースで ROWID と 呼ばれるものを使うことができます。例えば Oracle を使っているとき、このオプションに rowid を設定すれば、 Hiberante は update を高速化するために rowid という特別なカラムを使うことができます。 ROWID は詳細な実装であり、保存されたタプルの物理的な位置を表しています。

(20)

subselect (optional): maps an immutable and read-only entity to a database subselect. This is useful if you want to have a view instead of a base table. See below for more information.

(21)

abstract (オプション): <union-subclass> 階層内の抽象スーパークラスにマークするために使います。

永続クラスの名前にインターフェースを指定してもまったく問題ありません。そのときは <subclass> 要素を使って、そのインターフェースを実装するクラスを定義してください。 static な内部クラスでも永続化できます。そのときは標準形式、例えば eg.Foo$Bar を使ってクラス名を指定してください。

Here is how to do a virtual view (subselect) in XML:


<class name="Summary">
    <subselect>
        select item.name, max(bid.amount), count(*)
        from item
        join bid on bid.item_id = item.id
        group by item.name
    </subselect>
    <synchronize table="item"/>
    <synchronize table="bid"/>
    <id name="name"/>
    ...
</class>

The <subselect> is available both as an attribute and a nested mapping element.

Mapped classes must declare the primary key column of the database table. Most classes will also have a JavaBeans-style property holding the unique identifier of an instance.

Mark the identifier property with @Id.

@Entity

public class Person {
   @Id Integer getId() { ... }
   ...
}

In hbm.xml, use the <id> element which defines the mapping from that property to the primary key column.

<id
        name="(1)propertyName"
        type="(2)typename"
        column(3)="column_name"
        unsave(4)d-value="null|any|none|undefined|id_value"
        access(5)="field|property|ClassName">
        node="element-name|@attribute-name|element/@attribute|."

        <generator class="generatorClass"/>
</id>

1

name(オプション):識別子プロパティの名前。

2

type(オプション): Hibernate の型を示す名前。

3

column(オプション - デフォルトはプロパティ名): 主キーカラムの名前。

4

unsaved-value(オプション - デフォルトの値は sensible ): インスタンスが新しくインスタンス化された (セーブされていない)ことを示す、識別子プロパティの値。以前の Session でセーブまたはロードされた分離インスタンスと区別するために使います。

5

access (オプション - デフォルトは property ): Hibernate がプロパティの値にアクセスするために使用すべき戦略。

name 属性がなければ、クラスには識別子プロパティがないものとみなされます。

The unsaved-value attribute is almost never needed in Hibernate3 and indeed has no corresponding element in annotations.

You can also declare the identifier as a composite identifier. This allows access to legacy data with composite keys. Its use is strongly discouraged for anything else.

You can define a composite primary key through several syntaxes:

As you can see the last case is far from obvious. It has been inherited from the dark ages of EJB 2 for backward compatibilities and we recommend you not to use it (for simplicity sake).

Let's explore all three cases using examples.

Here is a simple example of @EmbeddedId.

@Entity

class User {
   @EmbeddedId
   @AttributeOverride(name="firstName", column=@Column(name="fld_firstname")
   UserId id;
   Integer age;
}
@Embeddable
class UserId implements Serializable {
   String firstName;
   String lastName;
}

You can notice that the UserId class is serializable. To override the column mapping, use @AttributeOverride.

An embedded id can itself contains the primary key of an associated entity.

@Entity

class Customer {
   @EmbeddedId CustomerId id;
   boolean preferredCustomer;
   @MapsId("userId")
   @JoinColumns({
      @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
      @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
   })
   @OneToOne User user;
}
@Embeddable
class CustomerId implements Serializable {
   UserId userId;
   String customerNumber;
   //implements equals and hashCode
}
@Entity 
class User {
   @EmbeddedId UserId id;
   Integer age;
}
@Embeddable
class UserId implements Serializable {
   String firstName;
   String lastName;
   //implements equals and hashCode
}

In the embedded id object, the association is represented as the identifier of the associated entity. But you can link its value to a regular association in the entity via the @MapsId annotation. The @MapsId value correspond to the property name of the embedded id object containing the associated entity's identifier. In the database, it means that the Customer.user and the CustomerId.userId properties share the same underlying column (user_fk in this case).

In practice, your code only sets the Customer.user property and the user id value is copied by Hibernate into the CustomerId.userId property.

While not supported in JPA, Hibernate lets you place your association directly in the embedded id component (instead of having to use the @MapsId annotation).

@Entity

class Customer {
   @EmbeddedId CustomerId id;
   boolean preferredCustomer;
}
@Embeddable
class CustomerId implements Serializable {
   @OneToOne
   @JoinColumns({
      @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
      @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
   }) 
   User user;
   String customerNumber;
   //implements equals and hashCode
}
@Entity 
class User {
   @EmbeddedId UserId id;
   Integer age;
}
@Embeddable
class UserId implements Serializable {
   String firstName;
   String lastName;
   //implements equals and hashCode
}

Let's now rewrite these examples using the hbm.xml syntax.


<composite-id
        name="propertyName"
        class="ClassName"
        mapped="true|false"
        access="field|property|ClassName"
        node="element-name|.">

        <key-property name="propertyName" type="typename" column="column_name"/>
        <key-many-to-one name="propertyName" class="ClassName" column="column_name"/>
        ......
</composite-id>

First a simple example:


<class name="User">
   <composite-id name="id" class="UserId">
      <key-property name="firstName" column="fld_firstname"/>
      <key-property name="lastName"/>
   </composite-id>
</class>

Then an example showing how an association can be mapped.


<class name="Customer">
   <composite-id name="id" class="CustomerId">
      <key-property name="firstName" column="userfirstname_fk"/>
      <key-property name="lastName" column="userfirstname_fk"/>
      <key-property name="customerNumber"/>
   </composite-id>

   <property name="preferredCustomer"/>

   <many-to-one name="user">
      <column name="userfirstname_fk" updatable="false" insertable="false"/>
      <column name="userlastname_fk" updatable="false" insertable="false"/>
   </many-to-one>
</class>

<class name="User">
   <composite-id name="id" class="UserId">
      <key-property name="firstName"/>
      <key-property name="lastName"/>
   </composite-id>

   <property name="age"/>
</class>

Notice a few things in the previous example:

The last example shows how to map association directly in the embedded id component.


<class name="Customer">
   <composite-id name="id" class="CustomerId">
      <key-many-to-one name="user">
         <column name="userfirstname_fk"/>
         <column name="userlastname_fk"/>
      </key-many-to-one>
      <key-property name="customerNumber"/>
   </composite-id>

   <property name="preferredCustomer"/>
</class>

<class name="User">
   <composite-id name="id" class="UserId">
      <key-property name="firstName"/>
      <key-property name="lastName"/>
   </composite-id>

   <property name="age"/>
</class>

This is the recommended approach to map composite identifier. The following options should not be considered unless some constraint are present.

Another, arguably more natural, approach is to place @Id on multiple properties of your entity. This approach is only supported by Hibernate (not JPA compliant) but does not require an extra embeddable component.

@Entity

class Customer implements Serializable {
   @Id @OneToOne
   @JoinColumns({
      @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
      @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
   })
   User user;
  
   @Id String customerNumber;
   boolean preferredCustomer;
   //implements equals and hashCode
}
@Entity 
class User {
   @EmbeddedId UserId id;
   Integer age;
}
@Embeddable
class UserId implements Serializable {
   String firstName;
   String lastName;
   //implements equals and hashCode
}

In this case Customer is its own identifier representation: it must implement Serializable and must implement equals() and hashCode().

In hbm.xml, the same mapping is:


<class name="Customer">
   <composite-id>
      <key-many-to-one name="user">
         <column name="userfirstname_fk"/>
         <column name="userlastname_fk"/>
      </key-many-to-one>
      <key-property name="customerNumber"/>
   </composite-id>

   <property name="preferredCustomer"/>
</class>

<class name="User">
   <composite-id name="id" class="UserId">
      <key-property name="firstName"/>
      <key-property name="lastName"/>
   </composite-id>

   <property name="age"/>
</class>

@IdClass on an entity points to the class (component) representing the identifier of the class. The properties marked @Id on the entity must have their corresponding property on the @IdClass. The return type of search twin property must be either identical for basic properties or must correspond to the identifier class of the associated entity for an association.

@Entity

@IdClass(CustomerId.class)
class Customer implements Serializable {
   @Id @OneToOne
   @JoinColumns({
      @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
      @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
   }) 
   User user;
  
   @Id String customerNumber;
   boolean preferredCustomer;
}
class CustomerId implements Serializable {
   UserId user;
   String customerNumber;
   //implements equals and hashCode
}
@Entity 
class User {
   @EmbeddedId UserId id;
   Integer age;
   //implements equals and hashCode
}
@Embeddable
class UserId implements Serializable {
   String firstName;
   String lastName;
   //implements equals and hashCode
}

Customer and CustomerId do have the same properties customerNumber as well as user. CustomerId must be Serializable and implement equals() and hashCode().

While not JPA standard, Hibernate let's you declare the vanilla associated property in the @IdClass.

@Entity

@IdClass(CustomerId.class)
class Customer implements Serializable {
   @Id @OneToOne
   @JoinColumns({
      @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
      @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
   }) 
   User user;
  
   @Id String customerNumber;
   boolean preferredCustomer;
}
class CustomerId implements Serializable {
   @OneToOne User user;
   String customerNumber;
   //implements equals and hashCode
}
@Entity 
class User {
   @EmbeddedId UserId id;
   Integer age;
   //implements equals and hashCode
}
@Embeddable
class UserId implements Serializable {
  String firstName;
  String lastName;
}

This feature is of limited interest though as you are likely to have chosen the @IdClass approach to stay JPA compliant or you have a quite twisted mind.

Here are the equivalent on hbm.xml files:


<class name="Customer">
   <composite-id class="CustomerId" mapped="true">
      <key-many-to-one name="user">
         <column name="userfirstname_fk"/>
         <column name="userlastname_fk"/>
      </key-many-to-one>
      <key-property name="customerNumber"/>
   </composite-id>

   <property name="preferredCustomer"/>
</class>

<class name="User">
   <composite-id name="id" class="UserId">
      <key-property name="firstName"/>
      <key-property name="lastName"/>
   </composite-id>

   <property name="age"/>
</class>

Hibernate can generate and populate identifier values for you automatically. This is the recommended approach over "business" or "natural" id (especially composite ids).

Hibernate offers various generation strategies, let's explore the most common ones first that happens to be standardized by JPA:

To mark an id property as generated, use the @GeneratedValue annotation. You can specify the strategy used (default to AUTO) by setting strategy.

@Entity

public class Customer {
   @Id @GeneratedValue
   Integer getId() { ... };
}
@Entity 
public class Invoice {
   @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
   Integer getId() { ... };
}

SEQUENCE and TABLE require additional configurations that you can set using @SequenceGenerator and @TableGenerator:

  • name: name of the generator

  • table / sequenceName: name of the table or the sequence (defaulting respectively to hibernate_sequences and hibernate_sequence)

  • catalog / schema:

  • initialValue: the value from which the id is to start generating

  • allocationSize: the amount to increment by when allocating id numbers from the generator

In addition, the TABLE strategy also let you customize:

  • pkColumnName: the column name containing the entity identifier

  • valueColumnName: the column name containing the identifier value

  • pkColumnValue: the entity identifier

  • uniqueConstraints: any potential column constraint on the table containing the ids

To link a table or sequence generator definition with an actual generated property, use the same name in both the definition name and the generator value generator as shown below.

@Id 

@GeneratedValue(
    strategy=GenerationType.SEQUENCE, 
    generator="SEQ_GEN")
@javax.persistence.SequenceGenerator(
    name="SEQ_GEN",
    sequenceName="my_sequence",
    allocationSize=20
)
public Integer getId() { ... }        

The scope of a generator definition can be the application or the class. Class-defined generators are not visible outside the class and can override application level generators. Application level generators are defined in JPA's XML deployment descriptors (see XXXXXX ???):

<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
)
         

If a JPA XML descriptor (like META-INF/orm.xml) is used to define the generators, EMP_GEN and SEQ_GEN are application level generators.

注意

Package level definition is not supported by the JPA specification. However, you can use the @GenericGenerator at the package level (see ???).

These are the four standard JPA generators. Hibernate goes beyond that and provide additional generators or additional options as we will see below. You can also write your own custom identifier generator by implementing org.hibernate.id.IdentifierGenerator.

To define a custom generator, use the @GenericGenerator annotation (and its plural counter part @GenericGenerators) that describes the class of the identifier generator or its short cut name (as described below) and a list of key/value parameters. When using @GenericGenerator and assigning it via @GeneratedValue.generator, the @GeneratedValue.strategy is ignored: leave it blank.

@Id @GeneratedValue(generator="system-uuid")

@GenericGenerator(name="system-uuid", strategy = "uuid")
public String getId() {
@Id @GeneratedValue(generator="trigger-generated")
@GenericGenerator(
    name="trigger-generated", 
    strategy = "select",
    parameters = @Parameter(name="key", value = "socialSecurityNumber")
)
public String getId() {

The hbm.xml approach uses the optional <generator> child element inside <id>. If any parameters are required to configure or initialize the generator instance, they are passed using the <param> element.


<id name="id" type="long" column="cat_id">
        <generator class="org.hibernate.id.TableHiLoGenerator">
                <param name="table">uid_table</param>
                <param name="column">next_hi_value_column</param>
        </generator>
</id>

すべてのジェネレータは、 org.hibernate.id.IdentifierGenerator インターフェースを実装します。これはとても単純なインターフェースなので、特別な実装を独自に用意するアプリケーションもあるかもしれません。しかし Hibernate は組み込みの実装をいくつも用意しています。組み込みのジェネレータには以下のショートカット名があります:

increment

long , short , int 型の識別子を生成します。これらは他のプロセスが同じテーブルにデータを挿入しないときだけユニークです。 クラスタ内では使わないでください

identity

DB2, MySQL, MS SQL Server, Sybase, HypersonicSQL の識別子カラムをサポートします。返される識別子の型は long , short , int のいずれかです。

sequence

DB2, PostgreSQL, Oracle, SAP DB, McKoi のシーケンスや、 Interbase のジェネレータを使用します。返される識別子の型は long , short , int のいずれかです。

hilo

long , short , int 型の識別子を効率的に生成する hi/lo アルゴリズムを使います。 hi 値のソースとして、テーブルとカラムを与えます(デフォルトではそれぞれ hibernate_unique_keynext_hi )。 hi/lo アルゴリズムは特定のデータベースに対してのみユニークな識別子を生成します。

seqhilo

long , short , int 型の識別子を効率的に生成する hi/lo アルゴリズムを使います。指定されたデータベースシーケンスを与えます。

uuid

Generates a 128-bit UUID based on a custom algorithm. The value generated is represented as a string of 32 hexidecimal digits. Users can also configure it to use a separator (config parameter "separator") which separates the hexidecimal digits into 8{sep}8{sep}4{sep}8{sep}4. Note specifically that this is different than the IETF RFC 4122 representation of 8-4-4-4-12. If you need RFC 4122 compliant UUIDs, consider using "uuid2" generator discussed below.

uuid2

Generates a IETF RFC 4122 compliant (variant 2) 128-bit UUID. The exact "version" (the RFC term) generated depends on the pluggable "generation strategy" used (see below). Capable of generating values as java.util.UUID, java.lang.String or as a byte array of length 16 (byte[16]). The "generation strategy" is defined by the interface org.hibernate.id.UUIDGenerationStrategy. The generator defines 2 configuration parameters for defining which generation strategy to use:

Out of the box, comes with the following strategies:

guid

MS SQL サーバーと MySQL でデータベースが生成する GUID 文字列を使用します。

native

使用するデータベースの性能により identitysequencehilo のいずれかが選ばれます。

assigned

save() が呼ばれる前に、アプリケーションがオブジェクトに識別子を代入できるようにします。 <generator> 要素が指定されていなければ、これがデフォルトの戦略になります。

select

あるユニークキーによる行の選択と主キーの値の復元により、データベーストリガが割り当てた主キーを取得します。

foreign

他の関連オブジェクトの識別子を使います。普通は、 <one-to-one> 主キー関連と組み合わせて使います。

sequence-identity

実際の値の生成のためにデータベースシーケンスを使用する特別なシーケンス生成戦略ですが、 JDBC3 getGeneratedKeys と結びついて、 INSERT 文の実行の一部として生成された識別子の値を実際に返します。この戦略は JDK 1.4 を対象とする Oracle 10g のドライバでサポートされていることが知られています。これらの INSERT 文でのコメントは Oracle のドライバのバグにより無効にされていることに注意してください。

Starting with release 3.2.3, there are 2 new generators which represent a re-thinking of 2 different aspects of identifier generation. The first aspect is database portability; the second is optimization Optimization means that you do not have to query the database for every request for a new identifier value. These two new generators are intended to take the place of some of the named generators described above, starting in 3.3.x. However, they are included in the current releases and can be referenced by FQN.

The first of these new generators is org.hibernate.id.enhanced.SequenceStyleGenerator which is intended, firstly, as a replacement for the sequence generator and, secondly, as a better portability generator than native. This is because native generally chooses between identity and sequence which have largely different semantics that can cause subtle issues in applications eyeing portability. org.hibernate.id.enhanced.SequenceStyleGenerator, however, achieves portability in a different manner. It chooses between a table or a sequence in the database to store its incrementing values, depending on the capabilities of the dialect being used. The difference between this and native is that table-based and sequence-based storage have the same exact semantic. In fact, sequences are exactly what Hibernate tries to emulate with its table-based generators. This generator has a number of configuration parameters:

The second of these new generators is org.hibernate.id.enhanced.TableGenerator, which is intended, firstly, as a replacement for the table generator, even though it actually functions much more like org.hibernate.id.MultipleHiLoPerTableGenerator, and secondly, as a re-implementation of org.hibernate.id.MultipleHiLoPerTableGenerator that utilizes the notion of pluggable optimizers. Essentially this generator defines a table capable of holding a number of different increment values simultaneously by using multiple distinctly keyed rows. This generator has a number of configuration parameters:

  • table_name (optional - defaults to hibernate_sequences): the name of the table to be used.

  • value_column_name (optional - defaults to next_val): the name of the column on the table that is used to hold the value.

  • segment_column_name (optional - defaults to sequence_name): the name of the column on the table that is used to hold the "segment key". This is the value which identifies which increment value to use.

  • segment_value (optional - defaults to default): The "segment key" value for the segment from which we want to pull increment values for this generator.

  • segment_value_length (optional - defaults to 255): Used for schema generation; the column size to create this segment key column.

  • initial_value (optional - defaults to 1): The initial value to be retrieved from the table.

  • increment_size (optional - defaults to 1): The value by which subsequent calls to the table should differ.

  • optimizer (optional - defaults to ??): See 「Identifier generator optimization」.

For identifier generators that store values in the database, it is inefficient for them to hit the database on each and every call to generate a new identifier value. Instead, you can group a bunch of them in memory and only hit the database when you have exhausted your in-memory value group. This is the role of the pluggable optimizers. Currently only the two enhanced generators (「Enhanced identifier generators」 support this operation.

  • none (generally this is the default if no optimizer was specified): this will not perform any optimizations and hit the database for each and every request.

  • hilo: applies a hi/lo algorithm around the database retrieved values. The values from the database for this optimizer are expected to be sequential. The values retrieved from the database structure for this optimizer indicates the "group number". The increment_size is multiplied by that value in memory to define a group "hi value".

  • pooled: as with the case of hilo, this optimizer attempts to minimize the number of hits to the database. Here, however, we simply store the starting value for the "next group" into the database structure rather than a sequential value in combination with an in-memory grouping algorithm. Here, increment_size refers to the values coming from the database.

When using long transactions or conversations that span several database transactions, it is useful to store versioning data to ensure that if the same entity is updated by two conversations, the last to commit changes will be informed and not override the other conversation's work. It guarantees some isolation while still allowing for good scalability and works particularly well in read-often write-sometimes situations.

You can use two approaches: a dedicated version number or a timestamp.

A version or timestamp property should never be null for a detached instance. Hibernate will detect any instance with a null version or timestamp as transient, irrespective of what other unsaved-value strategies are specified. Declaring a nullable version or timestamp property is an easy way to avoid problems with transitive reattachment in Hibernate. It is especially useful for people using assigned identifiers or composite keys.

You can add optimistic locking capability to an entity using the @Version annotation:

@Entity

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

The version property will be mapped to the OPTLOCK column, and the entity manager will use it to detect conflicting updates (preventing lost updates you might otherwise see with the last-commit-wins strategy).

The version column may be a numeric. Hibernate supports any kind of type provided that you define and implement the appropriate UserVersionType.

The application must not alter the version number set up by Hibernate in any way. To artificially increase the version number, check in Hibernate Entity Manager's reference documentation LockModeType.OPTIMISTIC_FORCE_INCREMENT or LockModeType.PESSIMISTIC_FORCE_INCREMENT.

If the version number is generated by the database (via a trigger for example), make sure to use @org.hibernate.annotations.Generated(GenerationTime.ALWAYS).

To declare a version property in hbm.xml, use:

<version
        column(1)="version_column"
        name="(2)propertyName"
        type="(3)typename"
        access(4)="field|property|ClassName"
        unsave(5)d-value="null|negative|undefined"
        genera(6)ted="never|always"
        insert(7)="true|false"
        node="element-name|@attribute-name|element/@attribute|."
/>

1

column (オプション - デフォルトはプロパティ名): バージョン番号を保持するカラムの名前。

2

name :永続クラスのプロパティの名前。

3

type (オプション - デフォルトは integer ):バージョン番号の型。

4

access (オプション - デフォルトは property ): Hibernate がプロパティの値にアクセスするために使用すべき戦略。

5

unsaved-value (optional - defaults to undefined): a version property value that indicates that an instance is newly instantiated (unsaved), distinguishing it from detached instances that were saved or loaded in a previous session. Undefined specifies that the identifier property value should be used.

6

generated (optional - defaults to never): specifies that this version property value is generated by the database. See the discussion of generated properties for more information.

7

insert (オプション - デフォルトは true ): SQLの insert 文にバージョンカラムを含めるべきかどうかを指定します。もしデータベースカラムのデフォルト値が 0 と定義されるときには、 false に設定すると良いでしょう。

Alternatively, you can use a timestamp. Timestamps are a less safe implementation of optimistic locking. However, sometimes an application might use the timestamps in other ways as well.

Simply mark a property of type Date or Calendar as @Version.

@Entity

public class Flight implements Serializable {
...
    @Version
    public Date getLastUpdate() { ... }
}           

When using timestamp versioning you can tell Hibernate where to retrieve the timestamp value from - database or JVM - by optionally adding the @org.hibernate.annotations.Source annotation to the property. Possible values for the value attribute of the annotation are org.hibernate.annotations.SourceType.VM and org.hibernate.annotations.SourceType.DB. The default is SourceType.DB which is also used in case there is no @Source annotation at all.

Like in the case of version numbers, the timestamp can also be generated by the database instead of Hibernate. To do that, use @org.hibernate.annotations.Generated(GenerationTime.ALWAYS).

In hbm.xml, use the <timestamp> element:

<timestamp
        column(1)="timestamp_column"
        name="(2)propertyName"
        access(3)="field|property|ClassName"
        unsave(4)d-value="null|undefined"
        source(5)="vm|db"
        genera(6)ted="never|always"
        node="element-name|@attribute-name|element/@attribute|."
/>

1

column(オプション - デフォルトはプロパティ名): タイムスタンプを保持するカラムの名前。

2

name : 永続クラスである Java の Date型または Timestamp 型 の、 JavaBeans スタイルプロパティの名前。

3

access (オプション - デフォルトは property ): Hibernate がプロパティの値にアクセスするために使用すべき戦略。

4

unsaved-value (オプション - デフォルトは null ): インスタンスが新しくインスタンス化された (セーブされていない)ことを示すバージョンプロパティの値。以前の Session でセーブまたはロードされた分離されたインスタンスと区別するために使われます。 ( undefined と指定すると、識別子プロパティの値が使われます。)

5

source (オプション - デフォルトは vm ): Hibernate はどこからタイムスタンプの値を取得するべきでしょうか?データベースからでしょうか、現在の JVM からでしょうか?データベースによるタイムスタンプは、 Hibernate が "次の値" を決定するためにデータベースをヒットしなければならないため、オーバヘッドを招きます。しかしクラスタ環境では JVM から取得するより安全です。データベースの現在のタイムスタンプの取得をサポートするすべての Dialect が知られているわけではないことに注意してください。また一方で、精密さを欠くために、ロックで使用するには安全でないものもあります (例えば Oracle 8 )。

6

generated (optional - defaults to never): specifies that this timestamp property value is actually generated by the database. See the discussion of generated properties for more information.

You need to decide which property needs to be made persistent in a given entity. This differs slightly between the annotation driven metadata and the hbm.xml files.

In the annotations world, every non static non transient property (field or method depending on the access type) of an entity is considered persistent, unless you annotate it as @Transient. Not having an annotation for your property is equivalent to the appropriate @Basic annotation.

The @Basic annotation allows you to declare the fetching strategy for a property. If set to LAZY, specifies that this property should be fetched lazily when the instance variable is first accessed. It requires build-time bytecode instrumentation, if your classes are not instrumented, property level lazy loading is silently ignored. The default is EAGER. You can also mark a property as not optional thanks to the @Basic.optional attribute. This will ensure that the underlying column are not nullable (if possible). Note that a better approach is to use the @NotNull annotation of the Bean Validation specification.

Let's look at a few examples:

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, a transient field, and lengthInMeter, a method annotated as @Transient, and will be ignored by the Hibernate. name, length, and firstname properties are mapped persistent and eagerly fetched (the default for simple properties). The detailedComment property value will be lazily fetched from the database once a lazy property of the entity is accessed for the first time. Usually you don't need to lazy simple properties (not to be confused with lazy association fetching). The recommended alternative is to use the projection capability of JP-QL (Java Persistence Query Language) or Criteria queries.

JPA support property mapping of all basic types supported by Hibernate (all basic Java types , their respective wrappers and serializable classes). Hibernate Annotations supports out of the box enum type mapping either into a ordinal column (saving the enum ordinal) or a string based column (saving the enum string representation): the persistence representation, defaulted to ordinal, can be overridden through the @Enumerated annotation as shown in the note property example.

In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data you might want to describe the expected precision in database. Temporal data can have DATE, TIME, or TIMESTAMP precision (ie the actual date, only the time, or both). Use the @Temporal annotation to fine tune that.

@Lob indicates that the property should be persisted in a Blob or a Clob depending on the property type: java.sql.Clob, Character[], char[] and java.lang.String will be persisted in a Clob. java.sql.Blob, Byte[], byte[] and Serializable type will be persisted in a Blob.

@Lob

public String getFullText() {
    return fullText;
}
@Lob
public byte[] getFullCode() {
    return fullCode;
}

If the property type implements java.io.Serializable and is not a basic type, and if the property is not annotated with @Lob, then the Hibernate serializable type is used.

You can also manually specify a type using the @org.hibernate.annotations.Type and some parameters if needed. @Type.type could be:

If you do not specify a type, Hibernate will use reflection upon the named property and guess the correct Hibernate type. Hibernate will attempt to interpret the name of the return class of the property getter using, in order, rules 2, 3, and 4.

@org.hibernate.annotations.TypeDef and @org.hibernate.annotations.TypeDefs allows you to declare type definitions. These annotations can be placed at the class or package level. Note that these definitions are global for the session factory (even when defined at the class level). If the type is used on a single entity, you can place the definition on the entity itself. Otherwise, it is recommended to place the definition at the package level. In the example below, when Hibernate encounters a property of class PhoneNumer, it delegates the persistence strategy to the custom mapping type PhoneNumberType. However, properties belonging to other classes, too, can delegate their persistence strategy to PhoneNumberType, by explicitly using the @Type annotation.

@TypeDef(

   name = "phoneNumber",
   defaultForType = PhoneNumber.class,
   typeClass = PhoneNumberType.class
)
@Entity
public class ContactDetails {
   [...]
   private PhoneNumber localPhoneNumber;
   @Type(type="phoneNumber")
   private OverseasPhoneNumber overseasPhoneNumber;
   [...]
}

The following example shows the usage of the parameters attribute to customize the TypeDef.

//in org/hibernate/test/annotations/entity/package-info.java

@TypeDefs(
    {
    @TypeDef(
        name="caster",
        typeClass = CasterStringType.class,
        parameters = {
            @Parameter(name="cast", value="lower")
        }
    )
    }
)
package org.hibernate.test.annotations.entity;
//in org/hibernate/test/annotations/entity/Forest.java
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.

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

By default the access type of a class hierarchy is defined by the position of the @Id or @EmbeddedId annotations. If these annotations are on a field, then only fields are considered for persistence and the state is accessed via the field. If there annotations are on a getter, then only the getters are considered for persistence and the state is accessed via the getter/setter. That works well in practice and is the recommended approach.

However in some situations, you need to:

The best use case is an embeddable class used by several entities that might not use the same access type. In this case it is better to force the access type at the embeddable class level.

To force the access type on a given class, use the @Access annotation as showed below:

@Entity

public class Order {
   @Id private Long id;
   public Long getId() { return id; }
   public void setId(Long id) { this.id = id; }
   @Embedded private Address address;
   public Address getAddress() { return address; }
   public void setAddress() { this.address = address; }
}
@Entity
public class User {
   private Long id;
   @Id public Long getId() { return id; }
   public void setId(Long id) { this.id = id; }
   private Address address;
   @Embedded public Address getAddress() { return address; }
   public void setAddress() { this.address = address; }
}
@Embeddable
@Access(AcessType.PROPERTY)
public class Address {
   private String street1;
   public String getStreet1() { return street1; }
   public void setStreet1() { this.street1 = street1; }
   private hashCode; //not persistent
}

You can also override the access type of a single property while keeping the other properties standard.

@Entity

public class Order {
   @Id private Long id;
   public Long getId() { return id; }
   public void setId(Long id) { this.id = id; }
   @Transient private String userId;
   @Transient private String orderId;
   @Access(AccessType.PROPERTY)
   public String getOrderNumber() { return userId + ":" + orderId; }
   public void setOrderNumber() { this.userId = ...; this.orderId = ...; }
}

In this example, the default access type is FIELD except for the orderNumber property. Note that the corresponding field, if any must be marked as @Transient or transient.

The column(s) used for a property mapping can be defined using the @Column annotation. Use it to override default values (see the JPA specification for more information on the defaults). You can use this annotation at the property level for properties that are:

@Entity

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

The name property is mapped to the flight_name column, which is not nullable, has a length of 50 and is not updatable (making the property immutable).

This annotation can be applied to regular properties as well as @Id or @Version properties.

@Column(
    name="colu(1)mnName";
    boolean un(2)ique() default false;
    boolean nu(3)llable() default true;
    boolean in(4)sertable() default true;
    boolean up(5)datable() default true;
    String col(6)umnDefinition() default "";
    String tab(7)le() default "";
    int length(8)() default 255;
    int precis(9)ion() default 0; // decimal precision
    int scale((10)) default 0; // decimal scale

1

name (optional): the column name (default to the property name)

2

unique (optional): set a unique constraint on this column or not (default false)

3

nullable (optional): set the column as nullable (default true).

4

insertable (optional): whether or not the column will be part of the insert statement (default true)

5

updatable (optional): whether or not the column will be part of the update statement (default true)

6

columnDefinition (optional): override the sql DDL fragment for this particular column (non portable)

7

table (optional): define the targeted table (default primary table)

8

length (optional): column length (default 255)

8

precision (optional): column decimal precision (default 0)

10

scale (optional): column decimal scale if useful (default 0)

<property> 要素は、クラスの永続的な JavaBean スタイルのプロパティを定義します。

<property
        name="(1)propertyName"
        column(2)="column_name"
        type="(3)typename"
        update(4)="true|false"
        insert(4)="true|false"
        formul(5)a="arbitrary SQL expression"
        access(6)="field|property|ClassName"
        lazy="(7)true|false"
        unique(8)="true|false"
        not-nu(9)ll="true|false"
        optimi(10)stic-lock="true|false"
        genera(11)ted="never|insert|always"
        node="element-name|@attribute-name|element/@attribute|."
        index="index_name"
        unique_key="unique_key_id"
        length="L"
        precision="P"
        scale="S"
/>

1

name: 小文字で始まるプロパティ名。

2

column(オプション - デフォルトはプロパティ名): マッピングされたデータベーステーブルのカラムの名前。ネストした <column> 要素でも指定できます。

3

type(オプション): Hibernate の型を示す名前。

4

update, insert (オプション - デフォルトは true ): マッピングされたカラムが SQL の UPDATEINSERT に含まれることを指定します。両方とも false に設定すると、同じカラムにマッピングされた他のプロパティやトリガや他のアプリケーションによって初期化された純粋な「導出」プロパティが可能になります。

5

formula(オプション): 計算 プロパティのための値を定義する SQL 式。計算されたプロパティは自身のカラムへのマッピングがありません。

6

access (オプション - デフォルトは property ): Hibernate がプロパティの値にアクセスするために使用すべき戦略。

7

lazy (オプション - デフォルトは false ): インスタンス変数に最初にアクセスしたときに、プロパティを遅延して取得するよう指定します。 (バイトコード実装を作成する時間が必要になります)。

8

unique (オプション):カラムにユニーク制約をつける DDL の生成を可能にします。また、 property-ref のターゲットとすることもできます。

9

not-null (optional): enables the DDL generation of a nullability constraint for the columns.

10

optimistic-lock (オプション - デフォルトは true ): このプロパティの更新に楽観ロックの取得を要求するかどうかを指定します。言い換えれば、このプロパティがダーティであるときにバージョンを増やすべきかを決定します。

11

generated (optional - defaults to never): specifies that this property value is actually generated by the database. See the discussion of generated properties for more information.

typename には以下の値が可能です:

型を指定しなければ、 Hibernate は正しい Hibernate の型を推測するために、指定されたプロパティに対してリフレクションを使います。 Hibernate はルール2, 3, 4をその順序に使い、 getter プロパティの返り値のクラスの名前を解釈しようとします。しかしこれで常に十分であるとは限りません。場合によっては、 type 属性が必要な場合があります。 (例えば Hibernate.DATEHibernate.TIMESTAMP を区別するため、またはカスタム型を指定するためなどです。)

access 属性で、実行時に Hibernate がどのようにプロパティにアクセスするかを制御できます。デフォルトでは Hibernate はプロパティの get/set のペアをコールします。 access="field" と指定すれば、 Hibernate はリフレクションを使い get/set のペアを介さずに、直接フィールドにアクセスします。インターフェース org.hibernate.property.PropertyAccessor を実装するクラスを指定することで、プロパティへのアクセスに独自の戦略を指定することができます。

特に強力な特徴は生成プロパティです。これらのプロパティは当然読み取り専用であり、プロパティの値はロード時に計算されます。計算を SQL 式として宣言すると、このプロパティはインスタンスをロードする SQL クエリの SELECT 句のサブクエリに変換されます:


<property name="totalPrice"
    formula="( SELECT SUM (li.quantity*p.price) FROM LineItem li, Product p
                WHERE li.productId = p.productId
                AND li.customerId = customerId
                AND li.orderNumber = orderNumber )"/>

特定のカラム(例では customerId がそれにあたります)のエイリアスを宣言することなく、エンティティ自身のテーブルを参照できることに注意してください。もし属性を使用したくなければ、ネストした <formula> マッピング要素を使えることにも注意してください。

Embeddable objects (or components) are objects whose properties are mapped to the same table as the owning entity's table. Components can, in turn, declare their own properties, components or collections

It is possible to declare an embedded component inside an entity and even override its column mapping. Component classes have to be annotated at the class level with the @Embeddable annotation. It is possible to override the column mapping of an embedded object for a particular entity using the @Embedded and @AttributeOverride annotation in the associated property:

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

An embeddable object inherits the access type of its owning entity (note that you can override that using the @Access annotation).

The Person entity has two component properties, homeAddress and bornIn. homeAddress property has not been annotated, but Hibernate will guess that it is a persistent component by looking for the @Embeddable annotation in the Address class. We also override the mapping of a column name (to bornCountryName) with the @Embedded and @AttributeOverride annotations for each mapped attribute of Country. As you can see, Country is also a nested component of Address, again using auto-detection by Hibernate and JPA defaults. Overriding columns of embedded objects of embedded objects is through dotted expressions.

@Embedded

    @AttributeOverrides( {
            @AttributeOverride(name="city", column = @Column(name="fld_city") ),
            @AttributeOverride(name="nationality.iso2", column = @Column(name="nat_Iso2") ),
            @AttributeOverride(name="nationality.name", column = @Column(name="nat_CountryName") )
            //nationality columns in homeAddress are overridden
    } )
    Address homeAddress;

Hibernate Annotations supports something that is not explicitly supported by the JPA specification. You can annotate a embedded object with the @MappedSuperclass annotation to make the superclass properties persistent (see @MappedSuperclass for more informations).

You can also use association annotations in an embeddable object (ie @OneToOne, @ManyToOne, @OneToMany or @ManyToMany). To override the association columns you can use @AssociationOverride.

If you want to have the same embeddable object type twice in the same entity, the column name defaulting will not work as several embedded objects would share the same set of columns. In plain JPA, you need to override at least one set of columns. Hibernate, however, allows you to enhance the default naming mechanism through the NamingStrategy interface. You can write a strategy that prevent name clashing in such a situation. DefaultComponentSafeNamingStrategy is an example of this.

If a property of the embedded object points back to the owning entity, annotate it with the @Parent annotation. Hibernate will make sure this property is properly loaded with the entity reference.

In XML, use the <component> element.

<component
        name="(1)propertyName"
        class=(2)"className"
        insert(3)="true|false"
        update(4)="true|false"
        access(5)="field|property|ClassName"
        lazy="(6)true|false"
        optimi(7)stic-lock="true|false"
        unique(8)="true|false"
        node="element-name|."
>

        <property ...../>
        <many-to-one .... />
        ........
</component>

1

name:プロパティ名。

2

class (オプション - デフォルトはリフレクションにより決定されるプロパティの型): コンポーネント(子)クラスの名前。

3

insert:マッピングされたカラムが SQL の INSERT に現れるようにするかどうかを指定します。

4

update:マッピングされたカラムが SQL の UPDATE に現れるようにするかどうかを指定します。

5

access (オプション - デフォルトは property ): Hibernate がプロパティの値にアクセスするために使用すべき戦略。

6

lazy (オプション - デフォルトは false ): インスタンス変数に最初にアクセスしたときに、コンポーネントを遅延してフェッチするよう指定します。 (バイトコード実装を作成する時間が必要になります)

7

optimistic-lock (オプション - デフォルトは true ): このプロパティの更新に、楽観ロックの取得を要求するかどうかを指定します。言い換えれば、このプロパティがダーティであるときにバージョンを増やすべきかを決定します。

8

unique (オプション - デフォルトは false ): コンポーネントのすべてのマッピングするカラムに、ユニーク制約が存在するかを指定します。

子の <property> タグで、子のクラスのプロパティをテーブルカラムにマッピングします。

<component> 要素は、親エンティティへ戻る参照として、コンポーネントのクラスのプロパティをマッピングする <parent> サブ要素を許可します。

The <dynamic-component> element allows a Map to be mapped as a component, where the property names refer to keys of the map. See 「動的コンポーネント」 for more information. This feature is not supported in annotations.

Java is a language supporting polymorphism: a class can inherit from another. Several strategies are possible to persist a class hierarchy:

With this approach the properties of all the subclasses in a given mapped class hierarchy are stored in a single table.

Each subclass declares its own persistent properties and subclasses. Version and id properties are assumed to be inherited from the root class. Each subclass in a hierarchy must define a unique discriminator value. If this is not specified, the fully qualified Java class name is used.

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

In hbm.xml, for the table-per-class-hierarchy mapping strategy, the <subclass> declaration is used. For example:

<subclass
        name="(1)ClassName"
        discri(2)minator-value="discriminator_value"
        proxy=(3)"ProxyInterface"
        lazy="(4)true|false"
        dynamic-update="true|false"
        dynamic-insert="true|false"
        entity-name="EntityName"
        node="element-name"
        extends="SuperclassName">

        <property .... />
        .....
</subclass>

1

name:サブクラスの完全修飾されたクラス名。

2

discriminator-value(オプション - デフォルトはクラス名): 個々のサブクラスを区別するための値。

3

proxy (オプション): 遅延初期化プロキシに使用するクラスやインターフェースを指定します。

4

lazy (オプション、デフォルトは true ): lazy="false" とすると、遅延フェッチが使用できません。

For information about inheritance mappings see 10章継承マッピング.

Discriminators are required for polymorphic persistence using the table-per-class-hierarchy mapping strategy. It declares a discriminator column of the table. The discriminator column contains marker values that tell the persistence layer what subclass to instantiate for a particular row. Hibernate Core supports the follwoing restricted set of types as discriminator column: string, character, integer, byte, short, boolean, yes_no, true_false.

Use the @DiscriminatorColumn to define the discriminator column as well as the discriminator type.

You can also use @DiscriminatorFormula to express in SQL a virtual discriminator column. This is particularly useful when the discriminator value can be extracted from one or more columns of the table. Both @DiscriminatorColumn and @DiscriminatorFormula are to be set on the root entity (once per persisted hierarchy).

@org.hibernate.annotations.DiscriminatorOptions allows to optionally specify Hibernate specific discriminator options which are not standardized in JPA. The available options are force and insert. The force attribute is useful if the table contains rows with "extra" discriminator values that are not mapped to a persistent class. This could for example occur when working with a legacy database. If force is set to true Hibernate will specify the allowed discriminator values in the SELECT query, even when retrieving all instances of the root class. The second option - insert - tells Hibernate whether or not to include the discriminator column in SQL INSERTs. Usually the column should be part of the INSERT statement, but if your discriminator column is also part of a mapped composite identifier you have to set this option to false.

Finally, use @DiscriminatorValue on each class of the hierarchy to specify the value stored in the discriminator column for a given entity. If you do not set @DiscriminatorValue on a class, the fully qualified class name is used.

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

In hbm.xml, the <discriminator> element is used to define the discriminator column or formula:

<discriminator
        column(1)="discriminator_column"
        type="(2)discriminator_type"
        force=(3)"true|false"
        insert(4)="true|false"
        formul(5)a="arbitrary sql expression"
/>

1

column(オプション - デフォルトは class ): 識別カラムの名前。

2

type (オプション - デフォルトは string ): Hibernate の型を示す名前。

3

force (オプション - デフォルトは false ): ルートクラスのすべてのインスタンスを検索する場合であっても、 Hibernate が使用できる識別カラムの指定を「強制」します。

4

insert (オプション - デフォルトは true ): もし識別カラムがマッピングする複合識別子の一部ならば、 false と設定してください。 (Hibernate に SQL の INSERT 内のカラムを含ませないよう伝えます。)

5

formula (オプション) 型が評価されるときに実行される任意の SQL 式。コンテンツベースの識別を可能にします。

識別カラムの実際の値は、 <class><subclass> 要素の discriminator-value 属性で指定されます。

formula 属性を使うと、行の型を評価するために任意の SQL 式を宣言できます:


<discriminator
    formula="case when CLASS_TYPE in ('a', 'b', 'c') then 0 else 1 end"
    type="integer"/>

Each subclass can also be mapped to its own table. This is called the table-per-subclass mapping strategy. An inherited state is retrieved by joining with the table of the superclass. A discriminator column is not required for this mapping strategy. Each subclass must, however, declare a table column holding the object identifier. The primary key of this table is also a foreign key to the superclass table and described by the @PrimaryKeyJoinColumns or the <key> element.

@Entity @Table(name="CATS")

@Inheritance(strategy=InheritanceType.JOINED)
public class Cat implements Serializable { 
    @Id @GeneratedValue(generator="cat-uuid") 
    @GenericGenerator(name="cat-uuid", strategy="uuid")
    String getId() { return id; }
    ...
}
@Entity @Table(name="DOMESTIC_CATS")
@PrimaryKeyJoinColumn(name="CAT")
public class DomesticCat extends Cat { 
    public String getName() { return name; }
}            

In hbm.xml, use the <joined-subclass> element. For example:

<joined-subclass
        name="(1)ClassName"
        table=(2)"tablename"
        proxy=(3)"ProxyInterface"
        lazy="(4)true|false"
        dynamic-update="true|false"
        dynamic-insert="true|false"
        schema="schema"
        catalog="catalog"
        extends="SuperclassName"
        persister="ClassName"
        subselect="SQL expression"
        entity-name="EntityName"
        node="element-name">

        <key .... >

        <property .... />
        .....
</joined-subclass>

1

name:サブクラスの完全修飾されたクラス名。

2

table :サブクラステーブルの名前。

3

proxy (オプション): 遅延初期化プロキシに使用するクラスやインターフェースを指定します。

4

lazy (オプション、デフォルトは true ): lazy="false" とすると、遅延フェッチが使用できません。

Use the <key> element to declare the primary key / foreign key column. The mapping at the start of the chapter would then be re-written as:


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="eg">

        <class name="Cat" table="CATS">
                <id name="id" column="uid" type="long">
                        <generator class="hilo"/>
                </id>
                <property name="birthdate" type="date"/>
                <property name="color" not-null="true"/>
                <property name="sex" not-null="true"/>
                <property name="weight"/>
                <many-to-one name="mate"/>
                <set name="kittens">
                        <key column="MOTHER"/>
                        <one-to-many class="Cat"/>
                </set>
                <joined-subclass name="DomesticCat" table="DOMESTIC_CATS">
                    <key column="CAT"/>
                    <property name="name" type="string"/>
                </joined-subclass>
        </class>

        <class name="eg.Dog">
                <!-- mapping for Dog could go here -->
        </class>

</hibernate-mapping>

For information about inheritance mappings see 10章継承マッピング.

A third option is to map only the concrete classes of an inheritance hierarchy to tables. This is called the table-per-concrete-class strategy. Each table defines all persistent states of the class, including the inherited state. In Hibernate, it is not necessary to explicitly map such inheritance hierarchies. You can map each class as a separate entity root. However, if you wish use polymorphic associations (e.g. an association to the superclass of your hierarchy), you need to use the union subclass mapping.

@Entity

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

Or in hbm.xml:

<union-subclass
        name="(1)ClassName"
        table=(2)"tablename"
        proxy=(3)"ProxyInterface"
        lazy="(4)true|false"
        dynamic-update="true|false"
        dynamic-insert="true|false"
        schema="schema"
        catalog="catalog"
        extends="SuperclassName"
        abstract="true|false"
        persister="ClassName"
        subselect="SQL expression"
        entity-name="EntityName"
        node="element-name">

        <property .... />
        .....
</union-subclass>

1

name:サブクラスの完全修飾されたクラス名。

2

table :サブクラステーブルの名前。

3

proxy (オプション): 遅延初期化プロキシに使用するクラスやインターフェースを指定します。

4

lazy (オプション、デフォルトは true ): lazy="false" とすると、遅延フェッチが使用できません。

このマッピング戦略では識別カラムやキーカラムは必要ありません。

For information about inheritance mappings see 10章継承マッピング.

This is sometimes useful to share common properties through a technical or a business superclass without including it as a regular mapped entity (ie no specific table for this entity). For that purpose you can map them as @MappedSuperclass.

@MappedSuperclass

public class BaseEntity {
    @Basic
    @Temporal(TemporalType.TIMESTAMP)
    public Date getLastUpdate() { ... }
    public String getLastUpdater() { ... }
    ...
}
@Entity class Order extends BaseEntity {
    @Id public Integer getId() { ... }
    ...
}

In database, this hierarchy will be represented as an Order table having the id, lastUpdate and lastUpdater columns. The embedded superclass property mappings are copied into their entity subclasses. Remember that the embeddable superclass is not the root of the hierarchy though.

You can override columns defined in entity superclasses at the root entity level using the @AttributeOverride annotation.

@MappedSuperclass

public class FlyingObject implements Serializable {
    public int getAltitude() {
        return altitude;
    }
    @Transient
    public int getMetricAltitude() {
        return metricAltitude;
    }
    @ManyToOne
    public PropulsionType getPropulsion() {
        return metricAltitude;
    }
    ...
}
@Entity
@AttributeOverride( name="altitude", column = @Column(name="fld_altitude") )
@AssociationOverride( 
   name="propulsion", 
   joinColumns = @JoinColumn(name="fld_propulsion_fk") 
)
public class Plane extends FlyingObject {
    ...
}

The altitude property will be persisted in an fld_altitude column of table Plane and the propulsion association will be materialized in a fld_propulsion_fk foreign key column.

You can define @AttributeOverride(s) and @AssociationOverride(s) on @Entity classes, @MappedSuperclass classes and properties pointing to an @Embeddable object.

In hbm.xml, simply map the properties of the superclass in the <class> element of the entity that needs to inherit them.

While not recommended for a fresh schema, some legacy databases force your to map a single entity on several tables.

Using the @SecondaryTable or @SecondaryTables class level annotations. To express that a column is in a particular table, use the table parameter of @Column or @JoinColumn.

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

In this example, name will be in MainCat. storyPart1 will be in Cat1 and storyPart2 will be in Cat2. Cat1 will be joined to MainCat using the cat_id as a foreign key, and Cat2 using id (ie the same column name, the MainCat id column has). Plus a unique constraint on storyPart2 has been set.

There is also additional tuning accessible via the @org.hibernate.annotations.Table annotation:

Make sure to use the secondary table name in the appliesto property

@Entity

@Table(name="MainCat")
@SecondaryTable(name="Cat1")
@org.hibernate.annotations.Table(
   appliesTo="Cat1",
   fetch=FetchMode.SELECT,
   optional=true)
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;
    }
}

In hbm.xml, use the <join> element.

<join
        table=(1)"tablename"
        schema(2)="owner"
        catalo(3)g="catalog"
        fetch=(4)"join|select"
        invers(5)e="true|false"
        option(6)al="true|false">

        <key ... />

        <property ... />
        ...
</join>

1

table :結合したテーブルの名前

2

schema (オプション): ルートの <hibernate-mapping> 要素で指定したスキーマ名をオーバーライドします。

3

catalog (オプション): ルートの <hibernate-mapping> 要素で指定したカタログ名をオーバーライドします。

4

fetch (オプション - デフォルトは join ): join を設定した場合、 Hibernate はデフォルトで、クラスやスーパークラスで定義された <join> を検索するのに内部結合を使い、サブクラスで定義された <join> を検索するのに外部結合を使います。 select を設定した場合には、 Hibernate はサブクラスで定義された <join> の選択に順次選択を使います。この場合、行がサブクラスのインスタンスを代表することがわかった場合にのみ発行されます。内部結合はクラスやそのスーパークラスで定義された <join> を検索するために使用します。

5

inverse (オプション - デフォルトは false ): もし可能であれば、 Hibernate はこの結合で定義されているプロパティに対し挿入や更新を行いません。

6

optional (オプション - デフォルトは false ): もし可能であれば、 Hibernate はこの結合で定義されたプロパティが null でない場合にのみ行を挿入し、そのプロパティの検索には常に外部結合を使用します。

例えば人のアドレスの情報を分離したテーブルにマッピングすることが可能です (すべてのプロパティに対して値型のセマンティクスを保持します):


<class name="Person"
    table="PERSON">

    <id name="id" column="PERSON_ID">...</id>

    <join table="ADDRESS">
        <key column="ADDRESS_ID"/>
        <property name="address"/>
        <property name="zip"/>
        <property name="country"/>
    </join>
    ...

この特徴はしばしばレガシーデータモデルに対してのみ有用ですが、クラスよりも少ないテーブルと、きめの細かいドメインモデルを推奨します。しかし後で説明するように、1つのクラス階層で継承のマッピング戦略を切り替える時には有用です。

To link one entity to an other, you need to map the association property as a to one association. In the relational model, you can either use a foreign key or an association table, or (a bit less common) share the same primary key value between the two entities.

To mark an association, use either @ManyToOne or @OnetoOne.

@ManyToOne and @OneToOne have a parameter named targetEntity which describes the target entity name. You usually don't need this parameter since the default value (the type of the property that stores the association) is good in almost all cases. However this is useful when you want to use interfaces as the return type instead of the regular entity.

Setting a value of the cascade attribute to any meaningful value other than nothing will propagate certain operations to the associated object. The meaningful values are divided into three categories.

By default, single point associations are eagerly fetched in JPA 2. You can mark it as lazily fetched by using @ManyToOne(fetch=FetchType.LAZY) in which case Hibernate will proxy the association and load it when the state of the associated entity is reached. You can force Hibernate not to use a proxy by using @LazyToOne(NO_PROXY). In this case, the property is fetched lazily when the instance variable is first accessed. This requires build-time bytecode instrumentation. lazy="false" specifies that the association will always be eagerly fetched.

With the default JPA options, single-ended associations are loaded with a subsequent select if set to LAZY, or a SQL JOIN is used for EAGER associations. You can however adjust the fetching strategy, ie how data is fetched by using @Fetch. FetchMode can be SELECT (a select is triggered when the association needs to be loaded) or JOIN (use a SQL JOIN to load the association while loading the owner entity). JOIN overrides any lazy attribute (an association loaded through a JOIN strategy cannot be lazy).

An ordinary association to another persistent class is declared using a

and a foreign key in one table is referencing the primary key column(s) of the target table.

@Entity

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

The @JoinColumn attribute is optional, the default value(s) is the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column in the owned side. In this example company_id because the property name is company and the column id of Company is id.

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

You can also map a to one association through an association table. This association table described by the @JoinTable annotation will contains a foreign key referencing back the entity table (through @JoinTable.joinColumns) and a a foreign key referencing the target entity table (through @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;
    }
    ...
}       

You can mark an association as mandatory by using the optional=false attribute. We recommend to use Bean Validation's @NotNull annotation as a better alternative however. As a consequence, the foreign key column(s) will be marked as not nullable (if possible).

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. This might be inconvenient for legacy and badly maintained schemas. You can ask Hibernate to ignore such elements instead of raising an exception using the @NotFound annotation.


Sometimes you want to delegate to your database the deletion of cascade when a given entity is deleted. In this case Hibernate generates a cascade delete constraint at the database level.


Foreign key constraints, while generated by Hibernate, have a fairly unreadable name. You can override the constraint name using @ForeignKey.


Sometimes, you want to link one entity to an other not by the target entity primary key but by a different unique key. You can achieve that by referencing the unique key column(s) in @JoinColumn.referenceColumnName.

@Entity

class Person {
   @Id Integer personNumber;
   String firstName;
   @Column(name="I")
   String initial;
   String lastName;
}
@Entity
class Home {
   @ManyToOne
   @JoinColumns({
      @JoinColumn(name="first_name", referencedColumnName="firstName"),
      @JoinColumn(name="init", referencedColumnName="I"),
      @JoinColumn(name="last_name", referencedColumnName="lastName"),
   })
   Person owner
}

This is not encouraged however and should be reserved to legacy mappings.

In hbm.xml, mapping an association is similar. The main difference is that a @OneToOne is mapped as <many-to-one unique="true"/>, let's dive into the subject.

<many-to-one
        name="(1)propertyName"
        column(2)="column_name"
        class=(3)"ClassName"
        cascad(4)e="cascade_style"
        fetch=(5)"join|select"
        update(6)="true|false"
        insert(6)="true|false"
        proper(7)ty-ref="propertyNameFromAssociatedClass"
        access(8)="field|property|ClassName"
        unique(9)="true|false"
        not-nu(10)ll="true|false"
        optimi(11)stic-lock="true|false"
        lazy="(12)proxy|no-proxy|false"
        not-fo(13)und="ignore|exception"
        entity(14)-name="EntityName"
        formul(15)a="arbitrary SQL expression"
        node="element-name|@attribute-name|element/@attribute|."
        embed-xml="true|false"
        index="index_name"
        unique_key="unique_key_id"
        foreign-key="foreign_key_name"
/>

1

name:プロパティ名。

2

column (オプション):外部キーカラムの名前。ネストした <column> カラムによっても指定されます。

3

class(オプション - デフォルトはリフレクションにより決定されるプロパティの型): 関連クラスの名前。

4

cascade(オプション): 親オブジェクトから関連オブジェクトへ、どの操作をカスケードするかを指定します。

5

fetch(オプション - デフォルトは select ): 外部結合フェッチと順次選択フェッチ(sequential select fetch)のどちらかを選択します。

6

update, insert(オプション - デフォルトは true ): マッピングされたカラムが SQL の UPDATE または INSERT 文に含まれることを指定します。両方とも false に設定すると、その値が同じカラムにマッピングされた他のプロパティやトリガや他のアプリケーションによって初期化された純粋な「導出」プロパティが可能になります。

7

property-ref: (オプション) この外部キーに加わる、関連クラスのプロパティの名前。指定されていない場合は、関連クラスの主キーが使用されます。

8

access (オプション - デフォルトは property ): Hibernate がプロパティの値にアクセスするために使用すべき戦略。

9

unique(オプション): 外部キーカラムに対してユニーク制約をつけた DDL の生成を可能にします。また、 property-ref のターゲットにすることもできます。これにより関連の多重度を効果的に一対一にします。

10

not-null (オプション): 外部キーカラムに対して、 null 値を許可する DDL の生成を可能にします。

11

optimistic-lock (オプション - デフォルトは true ): このプロパティの更新に楽観ロックの取得を要求するかどうかを指定します。言い換えれば、このプロパティがダーティであるときにバージョンを増やすべきかを決定します。

12

lazy (オプション - デフォルトは proxy ): デフォルトでは、多重度1の関連がプロキシとなります。 lazy="no-proxy" は、インスタンス変数に最初にアクセスしたときに、プロパティを遅延フェッチするよう指定します (ビルド時にバイトコード実装が必要になります)。 lazy="false" は関連を常に即時にフェッチするよう指定します。

13

not-found (オプション - デフォルトは exception): 参照先の行がない外部キーをどのように扱うかを指定します: ignore を指定すると、行がないことを関連がないものとして扱います。

14

entity-name (オプション):関連したクラスのエンティティ名。

15

formula (オプション): 計算された 外部キーに対して値を定義する SQL 式

Setting a value of the cascade attribute to any meaningful value other than none will propagate certain operations to the associated object. The meaningful values are divided into three categories. First, basic operations, which include: persist, merge, delete, save-update, evict, replicate, lock and refresh; second, special values: delete-orphan; and third,all comma-separated combinations of operation names: cascade="persist,merge,evict" or cascade="all,delete-orphan". See 「連鎖的な永続化」 for a full explanation. Note that single valued, many-to-one and one-to-one, associations do not support orphan delete.

典型的な many-to-one 宣言は次のようにシンプルです。:


<many-to-one name="product" class="Product" column="PRODUCT_ID"/>

property-ref 属性は、外部キーが関連付けられたテーブルの、主キーでないユニークキーを参照しているレガシーデータをマップするためにだけ使うべきです。これは醜いリレーショナルモデルです。例えば Product クラスが、主キーでないユニークなシリアルナンバーを持っていると仮定してみてください。( unique 属性は SchemaExport ツールを使った Hibernate の DDL 生成を制御します。)


<property name="serialNumber" unique="true" type="string" column="SERIAL_NUMBER"/>

以下のように OrderItem に対してマッピングを使えます:


<many-to-one name="product" property-ref="serialNumber" column="PRODUCT_SERIAL_NUMBER"/>

しかし、これは決して推奨できません。

参照したユニークキーが、関連するエンティティの多数のプロパティから構成される場合、指定した <properties> 要素内で、参照するプロパティをマッピングするべきです。

もし参照したユニークキーがコンポーネントのプロパティである場合は、プロパティのパスを指定できます:


<many-to-one name="owner" property-ref="identity.ssn" column="OWNER_SSN"/>

The second approach is to ensure an entity and its associated entity share the same primary key. In this case the primary key column is also a foreign key and there is no extra column. These associations are always one to one.


注意

Many people got confused by these primary key based one to one associations. They can only be lazily loaded if Hibernate knows that the other side of the association is always present. To indicate to Hibernate that it is the case, use @OneToOne(optional=false).

In hbm.xml, use the following mapping.

<one-to-one
        name="(1)propertyName"
        class=(2)"ClassName"
        cascad(3)e="cascade_style"
        constr(4)ained="true|false"
        fetch=(5)"join|select"
        proper(6)ty-ref="propertyNameFromAssociatedClass"
        access(7)="field|property|ClassName"
        formul(8)a="any SQL expression"
        lazy="(9)proxy|no-proxy|false"
        entity(10)-name="EntityName"
        node="element-name|@attribute-name|element/@attribute|."
        embed-xml="true|false"
        foreign-key="foreign_key_name"
/>

1

name:プロパティ名。

2

class(オプション - デフォルトはリフレクションにより決定されるプロパティの型): 関連クラスの名前。

3

cascade(オプション): 親オブジェクトから関連オブジェクトへ、どの操作をカスケードするかを指定します。

4

constrained(オプション): マッピングされたテーブルの主キーに対する外部キー制約が、関連クラスのテーブルを参照することを指定します。このオプションは save()delete() がカスケードされる順序に影響し、そして関連がプロキシされるかどうかにも影響します (そしてスキーマエクスポートツールにも使われます)。

5

fetch(オプション - デフォルトは select ): 外部結合フェッチと順次選択フェッチ(sequential select fetch)のどちらかを選択します。

6

property-ref(オプション): このクラスの主キーに結合された関連クラスのプロパティ名。指定されなければ、関連クラスの主キーが使われます。

7

access (オプション - デフォルトは property ): Hibernate がプロパティの値にアクセスするために使用すべき戦略。

8

formula (オプション): ほとんどすべての一対一関連はオーナーのエンティティの主キーへとマッピングされます。これ以外の稀な場合は、他のカラムや、複数のカラム、 SQL 構文を使った結合するための式を指定できます。(例は org.hibernate.test.onetooneformula を参照してください。)

9

lazy (オプション - デフォルトは proxy ): デフォルトでは、多重度1の関連がプロキシとなります。 lazy="no-proxy" は、インスタンス変数に最初にアクセスしたときに、プロパティを遅延フェッチするよう指定します (ビルド時にバイトコード実装が必要になります)。 lazy="false" は関連を常に即時にフェッチするよう指定します。 もし constrained="false" ならば、プロキシは使用不可能となり、関連を即時にフェッチすることに注意してください。

10

entity-name (オプション):関連したクラスのエンティティ名。

主キー関連には、特別なテーブルカラムは必要ありません。もし2つの行が関連により関係していれば、2つのテーブルは同じ主キーの値を共有します。そのため2つのオブジェクトを主キー関連によって関連付けたいのであれば、確実に同じ識別子の値を代入しなければなりません。

主キー関連を行うためには、以下のマッピングを EmployeePerson のそれぞれに追加してください。


<one-to-one name="person" class="Person"/>

<one-to-one name="employee" class="Employee" constrained="true"/>

ここで、 PERSON と EMPLOYEE テーブルの関係する行の主キーが同じであることを確実にしなければいけません。ここでは、 foreign という特殊な Hibernate 識別子生成戦略を使います:


<class name="person" table="PERSON">
    <id name="id" column="PERSON_ID">
        <generator class="foreign">
            <param name="property">employee</param>
        </generator>
    </id>
    ...
    <one-to-one name="employee"
        class="Employee"
        constrained="true"/>
</class>

Employee インスタンスが、 Personemployee プロパティで参照されるように、新しくセーブされた Person のインスタンスには同じ主キーの値が代入されます。新しくセーブする Person インスタンスは、その Personemployee プロパティが参照する Employee インスタンスとして同じ主キーが割り当てられます。

Although we recommend the use of surrogate keys as primary keys, you should try to identify natural keys for all entities. A natural key is a property or combination of properties that is unique and non-null. It is also immutable. Map the properties of the natural key as @NaturalId or map them inside the <natural-id> element. Hibernate will generate the necessary unique key and nullability constraints and, as a result, your mapping will be more self-documenting.

@Entity

public class Citizen {
    @Id
    @GeneratedValue
    private Integer id;
    private String firstname;
    private String lastname;
    
    @NaturalId
    @ManyToOne
    private State state;
    @NaturalId
    private String ssn;
    ...
}
//and later on query
List results = s.createCriteria( Citizen.class )
                .add( Restrictions.naturalId().set( "ssn", "1234" ).set( "state", ste ) )
                .list();

Or in XML,


<natural-id mutable="true|false"/>
        <property ... />
        <many-to-one ... />
        ......
</natural-id>

エンティティの自然キープロパティの比較には、 equals()hashCode() の実装を強くお勧めします。

このマッピングは自然主キーを使ったエンティティでの使用を意図していません。

There is one more type of property mapping. The @Any mapping defines a polymorphic association to classes from multiple tables. This type of mapping requires more than one column. The first column contains the type of the associated entity. The remaining columns contain the identifier. It is impossible to specify a foreign key constraint for this kind of association. This is not the usual way of mapping polymorphic associations and you should use this only in special cases. For example, for audit logs, user session data, etc.

The @Any annotation describes the column holding the metadata information. To link the value of the metadata information and an actual entity type, The @AnyDef and @AnyDefs annotations are used. The metaType attribute allows the application to specify a custom type that maps database column values to persistent classes that have identifier properties of the type specified by idType. You must specify the mapping from values of the metaType to class names.

@Any( metaColumn = @Column( name = "property_type" ), fetch=FetchType.EAGER )

@AnyMetaDef( 
    idType = "integer", 
    metaType = "string", 
    metaValues = {
        @MetaValue( value = "S", targetEntity = StringProperty.class ),
        @MetaValue( value = "I", targetEntity = IntegerProperty.class )
    } )
@JoinColumn( name = "property_id" )
public Property getMainProperty() {
    return mainProperty;
}

Note that @AnyDef can be mutualized and reused. It is recommended to place it as a package metadata in this case.

//on a package

@AnyMetaDef( name="property" 
    idType = "integer", 
    metaType = "string", 
    metaValues = {
        @MetaValue( value = "S", targetEntity = StringProperty.class ),
        @MetaValue( value = "I", targetEntity = IntegerProperty.class )
    } )
package org.hibernate.test.annotations.any;
//in a class
    @Any( metaDef="property", metaColumn = @Column( name = "property_type" ), fetch=FetchType.EAGER )
    @JoinColumn( name = "property_id" )
    public Property getMainProperty() {
        return mainProperty;
    }

The hbm.xml equivalent is:


<any name="being" id-type="long" meta-type="string">
    <meta-value value="TBL_ANIMAL" class="Animal"/>
    <meta-value value="TBL_HUMAN" class="Human"/>
    <meta-value value="TBL_ALIEN" class="Alien"/>
    <column name="table_name"/>
    <column name="id"/>
</any>
<any
        name="(1)propertyName"
        id-typ(2)e="idtypename"
        meta-t(3)ype="metatypename"
        cascad(4)e="cascade_style"
        access(5)="field|property|ClassName"
        optimi(6)stic-lock="true|false"
>
        <meta-value ... />
        <meta-value ... />
        .....
        <column .... />
        <column .... />
        .....
</any>

1

name: プロパティ名。

2

id-type: 識別子の型。

3

meta-type(オプション - デフォルトは string ): ディスクリミネータマッピングで許された型。

4

cascade(オプション - デフォルトは none ): カスケードのスタイル。

5

access (オプション - デフォルトは property ): Hibernate がプロパティの値にアクセスするために使用すべき戦略。

6

optimistic-lock (オプション - デフォルトは true ): このプロパティの更新に楽観ロックの取得を要求するかどうかを指定します。言い換えれば、このプロパティがダーティであるときにバージョンを増やすべきかを定義します。

<properties> 要素はクラスのプロパティの指定された、論理的なグルーピングを可能にします。この構造の最も重要な使用方法は、 property-ref のターゲットになるプロパティの結合を許可することです。それはまた、複数カラムのユニーク制約を定義する簡単な方法でもあります。

<properties
        name="(1)logicalName"
        insert(2)="true|false"
        update(3)="true|false"
        optimi(4)stic-lock="true|false"
        unique(5)="true|false"
>

        <property ...../>
        <many-to-one .... />
        ........
</properties>

1

name : グルーピングの論理名。実際のプロパティ名では ありません

2

insert:マッピングされたカラムが SQL の INSERT に現れるようにするかどうかを指定します。

3

update:マッピングされたカラムが SQL の UPDATE に現れるようにするかどうかを指定します。

4

optimistic-lock (オプション - デフォルトは true ): これらのプロパティの更新に楽観的ロックの取得を要求するかどうかを指定します。言い換えれば、このプロパティがダーティであるときにバージョンを増やすべきかを決定します。

5

unique (オプション - デフォルトは false ): コンポーネントのすべてのマッピングするカラムに、ユニーク制約が存在するかを指定します。

例えば、もし以下のような <properties> マッピングがあった場合:


<class name="Person">
    <id name="personNumber"/>

    ...
    <properties name="name"
            unique="true" update="false">
        <property name="firstName"/>
        <property name="initial"/>
        <property name="lastName"/>
    </properties>
</class>

主キーの代わりに Person テーブルのユニークキーへの参照を持つ、レガシーデータの関連を持つかもしれません。:


<many-to-one name="owner"
         class="Person" property-ref="name">
    <column name="firstName"/>
    <column name="initial"/>
    <column name="lastName"/>
</many-to-one>

しかし、このようなレガシーデータマッピングのコンテキスト外への使用は推奨しません。

The hbm.xml structure has some specificities naturally not present when using annotations, let's describe them briefly.

XML マッピングでは、お見せしたようなドキュメント型を必ず定義すべきです。実際の DTD は、上記の URL の hibernate-x.x.x/src/org/hibernate ディレクトリ、または hibernate.jar 内にあります。 Hibernate は常に、そのクラスパス内で DTD を探し始めます。インターネットにある DTD ファイルを探そうとしたなら、クラスパスの内容を見て、 DTD 宣言を確認してください。

前述したように、 Hibernate はまずクラスパス内で DTD を解決しようとします。 org.xml.sax.EntityResolver のカスタム実装を XML ファイルを読み込むための SAXReader に登録することによって、 DTD を解決します。このカスタムの EntityResolver は2つの異なるシステム ID 名前空間を認識します。

下記は、ユーザー名前空間を使った例です:


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" [
    <!ENTITY types SYSTEM "classpath://your/domain/types.xml">
]>

<hibernate-mapping package="your.domain">
    <class name="MyEntity">
        <id name="id" type="my-custom-id-type">
            ...
        </id>
    <class>
    &types;
</hibernate-mapping>

Where types.xml is a resource in the your.domain package and contains a custom typedef.

この要素にはいくつかオプション属性があります。 schema 属性と catalog 属性は、このマッピングが参照するテーブルが、この属性によって指定されたスキーマと(または)カタログに属することを指定します。この属性が指定されると、テーブル名は与えられたスキーマ名とカタログ名で修飾されます。これらの属性が指定されていなければ、テーブル名は修飾されません。 default-cascade 属性は、 cascade 属性を指定していないプロパティやコレクションに、どのカスケードスタイルを割り当てるかを指定します。 auto-import 属性は、クエリ言語内で修飾されていないクラス名を、デフォルトで使えるようにします。

<hibernate-mapping
         schem(1)a="schemaName"
         catal(2)og="catalogName"
         defau(3)lt-cascade="cascade_style"
         defau(4)lt-access="field|property|ClassName"
         defau(5)lt-lazy="true|false"
         auto-(6)import="true|false"
         packa(7)ge="package.name"
 />

1

schema(オプション):データベーススキーマの名前。

2

catalog (オプション):データベースカタログの名前。

3

default-cascade (オプション - デフォルトは none): デフォルトのカスケードスタイル。

4

default-access (オプション - デフォルトは property ): Hibernate がプロパティにアクセスする際に取るべき戦略。 PropertyAccessor を実装することでカスタマイズ可能。

5

default-lazy (オプション - デフォルトは true ): lazy 属性が指定されていないクラスやコレクションマッピングに対するデフォルト値。

6

auto-import (オプション - デフォルトは true):クエリ言語内で、(このマッピング内のクラスの)修飾されていないクラス名を使えるかどうかを指定します。

7

package (オプション): マッピングドキュメント内で修飾されていないクラス名に対して割り当てる、パッケージの接頭辞 (prefix) を指定します。

(修飾されていない)同じ名前の永続クラスが2つあるなら、 auto-import="false" を設定すべきです。2つのクラスに"インポートされた"同じ名前を割り当てようとすると、 Hibernate は例外を送出します。

hibernate-mapping 要素は、最初の例で示したようにいくつかの永続 <class> マッピングをネストできます。しかし、1つのマッピングファイルではただひとつの永続クラス(またはひとつのクラス階層)にマッピングするようにし、さらに永続スーパークラスの後で指定するべきでしょう(いくつかのツールはこのようなマッピングファイルを想定しています)。例えば次のようになります。: Cat.hbm.xml , Dog.hbm.xml , または継承を使うなら Animal.hbm.xml

The <key> element is featured a few times within this guide. It appears anywhere the parent mapping element defines a join to a new table that references the primary key of the original table. It also defines the foreign key in the joined table:

<key
        column(1)="columnname"
        on-del(2)ete="noaction|cascade"
        proper(3)ty-ref="propertyName"
        not-nu(4)ll="true|false"
        update(5)="true|false"
        unique(6)="true|false"
/>

1

column (オプション):外部キーカラムの名前。ネストした <column> カラムによっても指定されます。

2

on-delete (オプション, デフォルトは noaction): 外部キー制約がデータベースレベルでカスケード削除が可能かどうかを指定します。

3

property-ref (オプション): オリジナルテーブルの主キーではないカラムを参照する外部キーを指定します (レガシーデータに対して提供されます)。

4

not-null (オプション): 外部キーカラムが null 値を許容しないことを指定します (このことは外部キーが主キーの一部であることを暗黙的に示します)。

5

update (オプション): 外部キーを決して更新してはならないことを指定します (このことは外部キーが主キーの一部であることを暗黙的に示します)。

6

unique (オプション): 外部キーがユニーク制約を持つべきであることを指定します (このことは外部キーが主キーの一部であることを暗黙的に示します)。

削除のパフォーマンスが重要であるシステムには、すべてのキーを on-delete="cascade" と定義することを推奨します。そうすることで Hibernate は、 DELETE 文を毎回発行する代わりに、データベースレベルの ON CASCADE DELETE 制約を使用します。この特徴はバージョン付けられたデータに対する Hibernate の通常の楽観的ロック戦略を無視するということに注意してください。

not-nullupdate 属性は、単方向一対多関連の時には有用です。単方向一対多関連を null を許容しない外部キーにマッピングするときは、 <key not-null="true"> を使ってキーカラムを宣言 しなくてはなりません

In relation to the persistence service, Java language-level objects are classified into two groups:

エンティティ はエンティティへの参照を保持する、他のすべてのオブジェクトから独立して存在します。参照されないオブジェクトがガベージコレクトされてしまう性質を持つ通常の Java モデルと、これを比べてみてください。(親エンティティから子へ、セーブと削除が カスケード されうることを除いて)エンティティは明示的にセーブまたは削除されなければなりません。これは到達可能性によるオブジェクト永続化の ODMG モデルとは異なっています。大規模なシステムでアプリケーションオブジェクトが普通どのように使われるかにより密接に対応します。エンティティは循環と参照の共有をサポートします。またそれらはバージョン付けすることもできます。

エンティティの永続状態は他のエンティティや 型のインスタンスへの参照から構成されます。値はプリミティブ、コレクション (コレクションの内部ではなく)、コンポーネント、不変オブジェクトです。エンティティとは違い、値は(特にコレクションとコンポーネントにおいて)、到達可能性による永続化や削除が 行われます 。値オブジェクト(とプリミティブ)は、包含するエンティティと一緒に永続化や削除が行われるので、それらを独立にバージョン付けすることはできません。値には独立したアイデンティティがないので、複数のエンティティやコレクションがこれを共有することはできません。

これまで「永続クラス」という言葉をエンティティの意味で使ってきました。これからもそうしていきます。厳密に言うと、永続状態を持つユーザー定義のクラスのすべてがエンティティというわけではありません。 コンポーネント は値のセマンティクスを持つユーザー定義クラスです。 java.lang.String 型のプロパティもまた値のセマンティクスを持ちます。定義するなら、 JDK で提供されているすべての Java の型 (クラス) が値のセマンティクスを持つといえます。一方ユーザー定義型は、エンティティや値型のセマンティクスとともにマッピングできます。この決定はアプリケーション開発者次第です。そのクラスの1つのインスタンスへの共有参照は、ドメインモデル内のエンティティクラスに対する良いヒントになります。一方合成集約や集約は、通常値型へ変換されます。

本ドキュメントを通して、何度もこの概念を取り上げます。

Java 型のシステム (もしくは開発者が定義したエンティティと値型) を SQL /データベース型のシステムにマッピングすることは難しいです。 Hibernate は2つのシステムの架け橋を提供します。エンティティに対しては <class><subclass> などを使用します。値型に対しては <property><component> などを、通常 type と共に使います。この属性の値は Hibernate の マッピング型 の名前です。 Hibernate は (標準 JDK の値型に対して) 多くの自由なマッピングを提供します。後で見るように、自身のマッピング型を記述し、同様にカスタムの変換戦略を実装することができます。

コレクションを除く組み込みの Hibernate の型はすべて、 null セマンティクスをサポートします。

組み込みの 基本的なマッピング型 は大まかに以下のように分けられます。

integer, long, short, float, double, character, byte, boolean, yes_no, true_false

Java のプリミティブやラッパークラスから適切な(ベンダー固有の) SQL カラム型への型マッピング。 boolean, yes_notrue_false は、すべて Java の boolean または java.lang.Boolean の代替エンコードです。

string

java.lang.String から VARCHAR (または Oracle の VARCHAR2 )への型マッピング。

date, time, timestamp

java.util.Date とそのサブクラスから SQL 型の DATETIMETIMESTAMP (またはそれらと等価なもの) への型マッピング。

calendar, calendar_date

java.util.Calendar から SQL 型 の「 TIMESTAMPDATE (またはそれらと等価なもの)への型マッピング。

big_decimal, big_integer

java.math.BigDecimaljava.math.BigInteger から NUMERIC(または Oracle の NUMBER )への型マッピング。

locale, timezone, currency

java.util.Localejava.util.TimeZonejava.util.Currency から VARCHAR (または Oracle の VARCHAR2 )への型マッピング。 LocaleCurrency のインスタンスは、それらの ISO コードにマッピングされます。 TimeZone のインスタンスは、それらの ID にマッピングされます。

class

java.lang.Class から VARCHAR (または Oracle の VARCHAR2 )への型マッピング。 Class はその完全修飾された名前にマッピングされます。

binary

バイト配列は、適切な SQL のバイナリ型にマッピングされます。

text

Maps long Java strings to a SQL LONGVARCHAR or TEXT type.

image

Maps long byte arrays to a SQL LONGVARBINARY.

serializable

シリアライズ可能な Java 型は、適切な SQL のバイナリ型にマッピングされます。デフォルトで基本型ではないシリアライズ可能な Java クラスやインターフェースの名前を指定することで、 Hibernate の型を serializable とすることもできます。

clob, blob

JDBC クラス java.sql.Clobjava.sql.Blob に対する型マッピング。 blob や clob オブジェクトはトランザクションの外では再利用できないため、アプリケーションによっては不便かもしれません。(さらにはドライバサポートが一貫していません。)

materialized_clob

Maps long Java strings to a SQL CLOB type. When read, the CLOB value is immediately materialized into a Java string. Some drivers require the CLOB value to be read within a transaction. Once materialized, the Java string is available outside of the transaction.

materialized_blob

Maps long Java byte arrays to a SQL BLOB type. When read, the BLOB value is immediately materialized into a byte array. Some drivers require the BLOB value to be read within a transaction. Once materialized, the byte array is available outside of the transaction.

imm_date, imm_time, imm_timestamp, imm_calendar, imm_calendar_date, imm_serializable, imm_binary

ほとんどの場合に可変である Java の型に対する型マッピング。 Hibernate は不変な Java の型に対しては最適化を行い、アプリケーションはそれを不変オブジェクトとして扱います。例えば imm_timestamp としてマップしたインスタンスに対して、 Date.setTime() を呼び出してはなりません。プロパティの値を変更しその変更を永続化するためには、アプリケーションはプロパティに対して新しい (同一でない) オブジェクトを割り当てなければなりません。

エンティティとコレクションのユニークな識別子は、 binaryblobclob を除く、どんな基本型でも構いません。(複合識別子でも構いません。以下を見てください。)

基本的な値型には、 org.hibernate.Hibernate で定義された Type 定数がそれぞれあります。例えば、 Hibernate.STRINGstring 型を表現しています。

開発者が独自の値型を作成することは、比較的簡単です。例えば、 java.lang.BigInteger 型のプロパティを VARCHAR カラムに永続化したいかもしれません。 Hibernate はこのための組み込み型を用意していません。しかしカスタム型は、プロパティ(またはコレクションの要素)を1つのテーブルカラムにマッピングするのに制限はありません。そのため例えば、 java.lang.String 型の getName() / setName() Java プロパティを FIRST_NAMEINITIALSURNAME カラムに永続化できます。

カスタム型を実装するには、 org.hibernate.UserType または org.hibernate.CompositeUserType を実装し、型の完全修飾された名前を使ってプロパティを定義します。どのような種類のものが可能かを調べるには、 org.hibernate.test.DoubleStringType を確認してください。


<property name="twoStrings" type="org.hibernate.test.DoubleStringType">
    <column name="first_string"/>
    <column name="second_string"/>
</property>

<column> タグで、プロパティを複数のカラムへマッピングできることに注目してください。

CompositeUserTypeEnhancedUserTypeUserCollectionTypeUserVersionType インターフェースは、より特殊な使用法に対してのサポートを提供します。

マッピングファイル内で UserType へパラメータを提供できます。このためには、 UserTypeorg.hibernate.usertype.ParameterizedType を実装しなくてはなりません。カスタム型パラメータを提供するために、マッピングファイル内で <type> 要素を使用できます。


<property name="priority">
    <type name="com.mycompany.usertypes.DefaultValueIntegerType">
        <param name="default">0</param>
    </type>
</property>

UserType は、引数として渡された Properties オブジェクトから、 default で指定したパラメータに対する値を検索することができます。

特定の UserType を頻繁に使用するならば、短い名前を定義すると便利になるでしょう。 <typedef> 要素を使ってこのようなことが行えます。 Typedefs はカスタム型に名前を割り当てます。その型がパラメータを持つならば、パラメータのデフォルト値のリストを含むこともできます。


<typedef class="com.mycompany.usertypes.DefaultValueIntegerType" name="default_zero">
    <param name="default">0</param>
</typedef>

<property name="priority" type="default_zero"/>

プロパティのマッピングで型パラメータを使うことで、 typedef で提供されたパラメータをその都度オーバーライドすることが可能です。

Even though Hibernate's rich range of built-in types and support for components means you will rarely need to use a custom type, it is considered good practice to use custom types for non-entity classes that occur frequently in your application. For example, a MonetaryAmount class is a good candidate for a CompositeUserType, even though it could be mapped as a component. One reason for this is abstraction. With a custom type, your mapping documents would be protected against changes to the way monetary values are represented.

ある永続クラスに、一つ以上のマッピングを提供することが出来ます。この場合、マッピングする2つのエンティティのインスタンスを明確にするために、 エンティティ名 を指定しなければなりません (デフォルトではエンティティ名はクラス名と同じです。)。 Hibernate では、永続オブジェクトを扱うとき、クエリを書き込むとき、指定されたエンティティへの関連をマッピングするときに、エンティティ名を指定しなければなりません。

<class name="Contract" table="Contracts"
        entity-name="CurrentContract">
    ...
    <set name="history" inverse="true"
            order-by="effectiveEndDate desc">
        <key column="currentContractId"/>
        <one-to-many entity-name="HistoricalContract"/>
    </set>
</class>

<class name="Contract" table="ContractHistory"
        entity-name="HistoricalContract">
    ...
    <many-to-one name="currentContract"
            column="currentContractId"
            entity-name="CurrentContract"/>
</class>

関連が class の代わりに entity-name を使って、どのように指定されるのかに注目してください。

マッピングドキュメントでテーブルやカラムの名前をバッククォートで囲むことで、 Hibernate で生成された SQL 中の識別子を引用させることができます。 Hibernate は SQL の Dialect に対応する、正しい引用スタイルを使います(普通はダブルクォートですが、 SQL Server ではかぎ括弧、 MySQL ではバッククォートです)。


@Entity @Table(name="`Line Item`")
class LineItem {
   @id @Column(name="`Item Id`") Integer id;
   @Column(name="`Item #`") int itemNumber
}

<class name="LineItem" table="`Line Item`">
    <id name="id" column="`Item Id`"/><generator class="assigned"/></id>
    <property name="itemNumber" column="`Item #`"/>
    ...
</class>

生成プロパティとは、データベースによって生成された値を持つプロパティです。通常、 Hibernate アプリケーションは、データベースが値を生成したプロパティを含むオブジェクトを リフレッシュ する必要がありました。しかし、プロパティが生成されたということをマークすることで、アプリケーションはリフレッシュの責任を Hibernate に委譲します。基本的に、生成プロパティを持つと定義したエンティティに対して Hibernate が INSERT や UPDATE の SQL を発行した後すぐに、生成された値を読み込むための SELECT SQL が発行されます。

Properties marked as generated must additionally be non-insertable and non-updateable. Only versions, timestamps, and simple properties, can be marked as generated.

never (デフォルト) - 与えられたプロパティの値は、データベースから生成されないことを意味します。

insert: the given property value is generated on insert, but is not regenerated on subsequent updates. Properties like created-date fall into this category. Even though version and timestamp properties can be marked as generated, this option is not available.

always - 挿入時も更新時もプロパティの値が生成されることを示します。

To mark a property as generated, use @Generated.

Hibernate allows you to customize the SQL it uses to read and write the values of columns mapped to simple properties. For example, if your database provides a set of data encryption functions, you can invoke them for individual columns like this:

@Entity

class CreditCard {
   @Column(name="credit_card_num")
   @ColumnTransformer(
      read="decrypt(credit_card_num)", 
      write="encrypt(?)")
   public String getCreditCardNumber() { return creditCardNumber; }
   public void setCreditCardNumber(String number) { this.creditCardNumber = number; }
   private String creditCardNumber;
}

or in XML


<property name="creditCardNumber">
        <column 
          name="credit_card_num"
          read="decrypt(credit_card_num)"
          write="encrypt(?)"/>
</property>

注意

You can use the plural form @ColumnTransformers if more than one columns need to define either of these rules.

If a property uses more that one column, you must use the forColumn attribute to specify which column, the expressions are targeting.

@Entity

class User {
   @Type(type="com.acme.type.CreditCardType")
   @Columns( {
      @Column(name="credit_card_num"),
      @Column(name="exp_date") } )
   @ColumnTransformer(
      forColumn="credit_card_num", 
      read="decrypt(credit_card_num)", 
      write="encrypt(?)")
   public CreditCard getCreditCard() { return creditCard; }
   public void setCreditCard(CreditCard card) { this.creditCard = card; }
   private CreditCard creditCard;
}

Hibernate applies the custom expressions automatically whenever the property is referenced in a query. This functionality is similar to a derived-property formula with two differences:

  • The property is backed by one or more columns that are exported as part of automatic schema generation.

  • The property is read-write, not read-only.

The write expression, if specified, must contain exactly one '?' placeholder for the value.

Hibernate のスキーマエボリューションツールと連動することで、任意のデータベースオブジェクト(トリガーやストアドプロシージャなど)の CREATE と DROP により、 Hibernate のマッピングファイル内のユーザースキーマをすべて定義することが出来ます。主にトリガやストアドプロシージャのようなデータベースオブジェクトを生成や削除することを意図していますが、実際には java.sql.Statement.execute() メソッドによって実行できる任意の SQL コマンド(ALTER、INSERTなど)が実行できます。補助的なデータベースオブジェクトを定義するための、2つの基本的な方法があります。

1つ目の方法は、 CREATE と DROP コマンドをマッピングファイルの外に、明示的に記載することです:


<hibernate-mapping>
    ...
    <database-object>
        <create>CREATE TRIGGER my_trigger ...</create>
        <drop>DROP TRIGGER my_trigger</drop>
    </database-object>
</hibernate-mapping>

2つ目の方法は、 CREATE と DROP コマンドの組み立て方を知っているカスタムクラスを提供することです。このカスタムクラスは org.hibernate.mapping.AuxiliaryDatabaseObject インタフェースを実装しなければなりません。


<hibernate-mapping>
    ...
    <database-object>
        <definition class="MyTriggerDefinition"/>
    </database-object>
</hibernate-mapping>

さらに、あるデータベース方言が使用される時にだけ適用するといったように、データベースオブジェクトが使われるケースを限定できます。


<hibernate-mapping>
    ...
    <database-object>
        <definition class="MyTriggerDefinition"/>
        <dialect-scope name="org.hibernate.dialect.Oracle9iDialect"/>
        <dialect-scope name="org.hibernate.dialect.Oracle10gDialect"/>
    </database-object>
</hibernate-mapping>