Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lect17-hibernate-orm / more / hibernate_reference.pdf
Скачиваний:
57
Добавлен:
18.03.2015
Размер:
2.2 Mб
Скачать

Identifiers

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

5.1.2.2. Identifier generator

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:

IDENTITY: supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

SEQUENCE (called seqhilo in Hibernate): uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.

81

Chapter 5. Basic O/R Mapping

TABLE (called MultipleHiLoPerTableGenerator in Hibernate) : uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database.

AUTO: selects IDENTITY, SEQUENCE or TABLE depending upon the capabilities of the underlying database.

Important

We recommend all new projects to use the new enhanced identifier generators. They are deactivated by default for entities using annotations but can be activated using hibernate.id.new_generator_mappings=true. These new generators are more efficient and closer to the JPA 2 specification semantic.

However they are not backward compatible with existing Hibernate based application (if a sequence or a table is used for id generation). See XXXXXXX ???

for more information on how to activate them.

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

82

Identifiers

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(

83

Chapter 5. Basic O/R Mapping

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.

Note

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>

84

Соседние файлы в папке more