Hibernate.orgCommunity Documentation
Object/relational mappings can be defined in three approaches:
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 { ... }
<?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>
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; }
}
@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; }
}
@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; }
...
}
<class name="ClassName" table=
"tableName" discri
minator-value="discriminator_value" mutabl
e="true|false" schema
="owner" catalo
g="catalog" proxy=
"ProxyInterface" dynami
c-update="true|false" dynami
c-insert="true|false" select
-before-update="true|false" polymo
rphism="implicit|explicit" where=
"arbitrary sql where condition" persis
ter="PersisterClass" batch-
size="N" optimi
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" />
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
(16) |
|
(17) |
|
(18) |
|
(19) |
|
(20) |
|
(21) |
|
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.
Mark the identifier property with
@Id
.
@Entity
public class Person {
@Id Integer getId() { ... }
...
}
<id name="propertyName" type="
typename" column
="column_name" unsave
d-value="null|any|none|undefined|id_value" access
="field|property|ClassName"> node="element-name|@attribute-name|element/@attribute|." <generator class="generatorClass"/> </id>
| |
| |
| |
| |
|
If the name
attribute is missing, it is assumed
that the class has no identifier property.
You can define a composite primary key through several syntaxes:
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;
}
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
}
@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>
<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>
@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 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>
@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
}
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;
}
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>
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
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>
increment
identity
sequence
hilo
seqhilo
uuid
uuid2
Out of the box, comes with the following strategies:
org.hibernate.id.uuid.CustomVersionOneStrategy
- generates "version 1" UUID values, using IP address
since mac address not available. If you need mac
address to be used, consider leveraging one of the
existing third party UUID generators which sniff out
mac address and integrating it via the
org.hibernate.id.UUIDGenerationStrategy
contract. Two such libraries known at time of this
writing include http://johannburkard.de/software/uuid/
and http://commons.apache.org/sandbox/id/uuid.html
guid
uses a database-generated GUID string on MS SQL Server and MySQL.
native
selects identity
,
sequence
or hilo
depending upon the capabilities of the underlying
database.
assigned
lets the application assign an identifier to the
object before save()
is called. This is
the default strategy if no
<generator>
element is
specified.
select
retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value.
foreign
uses the identifier of another associated object. It
is usually used in conjunction with a
<one-to-one>
primary key
association.
sequence-identity
a specialized sequence generation strategy that utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to return the generated identifier value as part of the insert statement execution. This strategy is only supported on Oracle 10g drivers targeted for JDK 1.4. Comments on these insert statements are disabled due to a bug in the Oracle drivers.
<id name="id" type="long" column="cat_id">
<generator class="hilo">
<param name="table">hi_value</param>
<param name="column">next_value</param>
<param name="max_lo">100</param>
</generator>
</id>
<id name="id" type="long" column="cat_id">
<generator class="seqhilo">
<param name="sequence">hi_value</param>
<param name="max_lo">100</param>
</generator>
</id>
<id name="id" type="long" column="person_id">
<generator class="sequence">
<param name="sequence">person_id_sequence</param>
</generator>
</id>
<id name="id" type="long" column="person_id" unsaved-value="0">
<generator class="identity"/>
</id>
Hibernate does not generate DDL with triggers. It is for legacy schemas only.
<id name="id" type="long" column="person_id">
<generator class="select">
<param name="key">socialSecurityNumber</param>
</generator>
</id>
@Entity
class MedicalHistory implements Serializable {
@Id @OneToOne
@JoinColumn(name = "person_id")
Person patient;
}
@Entity
public class Person implements Serializable {
@Id @GeneratedValue Integer id;
}
@Entity
class MedicalHistory implements Serializable {
@Id Integer id;
@MapsId @OneToOne
@JoinColumn(name = "patient_id")
Person patient;
}
@Entity
class Person {
@Id @GeneratedValue Integer id;
}
In hbm.xml use the following approach:
<class name="MedicalHistory">
<id name="id">
<generator class="foreign">
<param name="property">patient</param>
</generator>
</id>
<one-to-one name="patient" class="Person" constrained="true"/>
</class>
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 Section 5.1.2.3.1, “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 (Section 5.1.2.3, “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.
@Entity
public class CustomerInventory implements Serializable {
@Id
@TableGenerator(name = "inventory",
table = "U_SEQUENCES",
pkColumnName = "S_ID",
valueColumnName = "S_NEXTNUM",
pkColumnValue = "inventory",
allocationSize = 1000)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "inventory")
Integer id;
@Id @ManyToOne(cascade = CascadeType.MERGE)
Customer customer;
}
@Entity
public class Customer implements Serializable {
@Id
private int id;
}
You can also generate properties inside an
@EmbeddedId
class.
You can use two approaches: a dedicated version number or a timestamp.
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() { ... }
}
To declare a version property in hbm.xml, use:
<version column="version_column" name="
propertyName" type="
typename" access
="field|property|ClassName" unsave
d-value="null|negative|undefined" genera
ted="never|always" insert
="true|false" node="element-name|@attribute-name|element/@attribute|." />
| |
| |
| |
| |
| |
| |
|
Simply mark a property of type Date
or
Calendar
as
@Version
.
@Entity
public class Flight implements Serializable {
...
@Version
public Date getLastUpdate() { ... }
}
In hbm.xml, use the <timestamp>
element:
<timestamp column="timestamp_column" name="
propertyName" access
="field|property|ClassName" unsave
d-value="null|undefined" source
="vm|db" genera
ted="never|always" node="element-name|@attribute-name|element/@attribute|." />
| |
| |
| |
| |
| |
|
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
@Lob
public String getFullText() {
return fullText;
}
@Lob
public byte[] getFullCode() {
return fullCode;
}
@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() {
...
}
@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;
...
}
However in some situations, you need to:
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
}
@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 = ...; }
}
@Entity
public class Flight implements Serializable {
...
@Column(updatable = false, name = "flight_name", nullable = false, length=50)
public String getName() { ... }
This annotation can be applied to regular properties as well
as @Id
or @Version
properties.
@Column( name="columnName"; boolean un
ique() default false; boolean nu
llable() default true; boolean in
sertable() default true; boolean up
datable() default true; String col
umnDefinition() default ""; String tab
le() default ""; int length
() default 255; int precis
ion() default 0; // decimal precision int scale(
) default 0; // decimal scale
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
@Formula("obj_length * obj_height * obj_width")
public long getObjectVolume()
The SQL fragment can be as complex as you want and even include subselects.
The <property>
element declares a
persistent JavaBean style property of the class.
<property name="propertyName" column
="column_name" type="
typename" update
="true|false" insert
="true|false" formul
a="arbitrary SQL expression" access
="field|property|ClassName" lazy="
true|false" unique
="true|false" not-nu
ll="true|false" optimi
stic-lock="true|false" genera
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" />
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
<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 )"/>
@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; }
...
}
@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;
In XML, use the <component>
element.
<component name="propertyName" class=
"className" insert
="true|false" update
="true|false" access
="field|property|ClassName" lazy="
true|false" optimi
stic-lock="true|false" unique
="true|false" node="element-name|." > <property ...../> <many-to-one .... /> ........ </component>
| |
| |
| |
| |
| |
| |
| |
|
The child <property>
tags map properties
of the child class to table columns.
The <dynamic-component>
element allows a
Map
to be mapped as a component, where the property
names refer to keys of the map. See Section 9.5, “Dynamic components” for more information. This feature is
not supported in annotations.
@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 { ... }
<subclass name="ClassName" discri
minator-value="discriminator_value" proxy=
"ProxyInterface" lazy="
true|false" dynamic-update="true|false" dynamic-insert="true|false" entity-name="EntityName" node="element-name" extends="SuperclassName"> <property .... /> ..... </subclass>
| |
| |
| |
|
For information about inheritance mappings see Chapter 10, Inheritance mapping.
Use the @DiscriminatorColumn
to define
the discriminator column as well as the discriminator type.
@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="discriminator_column" type="
discriminator_type" force=
"true|false" insert
="true|false" formul
a="arbitrary sql expression" />
| |
| |
| |
| |
|
<discriminator
formula="case when CLASS_TYPE in ('a', 'b', 'c') then 0 else 1 end"
type="integer"/>
@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="ClassName" table=
"tablename" proxy=
"ProxyInterface" lazy="
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>
| |
| |
| |
|
<?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 Chapter 10, Inheritance mapping.
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Flight implements Serializable { ... }
<union-subclass name="ClassName" table=
"tablename" proxy=
"ProxyInterface" lazy="
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>
| |
| |
| |
|
No discriminator column or key column is required for this mapping strategy.
For information about inheritance mappings see Chapter 10, Inheritance mapping.
@MappedSuperclass
public class BaseEntity {
@Basic
@Temporal(TemporalType.TIMESTAMP)
public Date getLastUpdate() { ... }
public String getLastUpdater() { ... }
...
}
@Entity class Order extends BaseEntity {
@Id public Integer getId() { ... }
...
}
@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 {
...
}
@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;
}
}
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="tablename" schema
="owner" catalo
g="catalog" fetch=
"join|select" invers
e="true|false" option
al="true|false"> <key ... /> <property ... /> ... </join>
| |
| |
| |
| |
| |
|
<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>
...
To mark an association, use either
@ManyToOne
or
@OnetoOne
.
comma-separated combinations of operation names:
cascade="persist,merge,evict"
or
cascade="all,delete-orphan"
. See Section 11.11, “Transitive persistence” for a full explanation. Note
that single valued many-to-one associations do not support orphan
delete.
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;
}
...
}
@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 {
...
}
@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;
}
...
}
@Entity
public class Ticket implements Serializable {
@ManyToOne
@JoinColumnOrFormula(formula="(firstname + ' ' + lastname)")
public Person getOwner() {
return person;
}
...
}
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.
Example 5.2. @OnDelete annotation
@Entity
public class Child {
...
@ManyToOne
@OnDelete(action=OnDeleteAction.CASCADE)
public Parent getParent() { ... }
...
}
Foreign key constraints, while generated by Hibernate, have a
fairly unreadable name. You can override the constraint name using
@ForeignKey
.
Example 5.3. @ForeignKey annotation
@Entity
public class Child {
...
@ManyToOne
@ForeignKey(name="FK_PARENT")
public Parent getParent() { ... }
...
}
alter table Child add constraint FK_PARENT foreign key (parent_id) references Parent
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="propertyName" column
="column_name" class=
"ClassName" cascad
e="cascade_style" fetch=
"join|select" update
="true|false" insert
="true|false" proper
ty-ref="propertyNameFromAssociatedClass" access
="field|property|ClassName" unique
="true|false" not-nu
ll="true|false" optimi
stic-lock="true|false" lazy="
proxy|no-proxy|false" not-fo
und="ignore|exception" entity
-name="EntityName" formul
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" />
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
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 Section 11.11, “Transitive persistence” for a full explanation. Note that
single valued, many-to-one and one-to-one, associations do not support
orphan delete.
Here is an example of a typical many-to-one
declaration:
<many-to-one name="product" class="Product" column="PRODUCT_ID"/>
The property-ref
attribute should only be
used for mapping legacy data where a foreign key refers to a unique
key of the associated table other than the primary key. This is a
complicated and confusing relational model. For example, if the
Product
class had a unique serial number that is
not the primary key. The unique
attribute controls
Hibernate's DDL generation with the SchemaExport tool.
<property name="serialNumber" unique="true" type="string" column="SERIAL_NUMBER"/>
Then the mapping for OrderItem
might
use:
<many-to-one name="product" property-ref="serialNumber" column="PRODUCT_SERIAL_NUMBER"/>
This is not encouraged, however.
If the referenced unique key comprises multiple properties of
the associated entity, you should map the referenced properties inside
a named <properties>
element.
If the referenced unique key is the property of a component, you can specify a property path:
<many-to-one name="owner" property-ref="identity.ssn" column="OWNER_SSN"/>
@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();
<natural-id mutable="true|false"/>
<property ... />
<many-to-one ... />
......
</natural-id>
This mapping is not intended for use with entities that have natural primary keys.
@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;
}
//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;
}
<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="propertyName" id-typ
e="idtypename" meta-t
ype="metatypename" cascad
e="cascade_style" access
="field|property|ClassName" optimi
stic-lock="true|false" > <meta-value ... /> <meta-value ... /> ..... <column .... /> <column .... /> ..... </any>
| |
| |
| |
| |
| |
|
<properties name="logicalName" insert
="true|false" update
="true|false" optimi
stic-lock="true|false" unique
="true|false" > <property ...../> <many-to-one .... /> ........ </properties>
| |
| |
| |
| |
|
For example, if we have the following
<properties>
mapping:
<class name="Person">
<id name="personNumber"/>
...
<properties name="name"
unique="true" update="false">
<property name="firstName"/>
<property name="initial"/>
<property name="lastName"/>
</properties>
</class>
<many-to-one name="owner"
class="Person" property-ref="name">
<column name="firstName"/>
<column name="initial"/>
<column name="lastName"/>
</many-to-one>
@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
}
The use of this outside the context of mapping legacy data is not recommended.
The following is an example of utilizing user namespacing:
<?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.
<hibernate-mapping schema="schemaName" catal
og="catalogName" defau
lt-cascade="cascade_style" defau
lt-access="field|property|ClassName" defau
lt-lazy="true|false" auto-
import="true|false" packa
ge="package.name" />
| |
| |
| |
| |
| |
| |
|
<key column="columnname" on-del
ete="noaction|cascade" proper
ty-ref="propertyName" not-nu
ll="true|false" update
="true|false" unique
="true|false" />
| |
| |
| |
| |
| |
|
<import class="java.lang.Object" rename="Universe"/>
<import class="ClassName" rename
="ShortName" />
| |
|
<column
name="column_name"
length="N"
precision="N"
scale="N"
not-null="true|false"
unique="true|false"
unique-key="multicolumn_unique_key_name"
index="index_name"
sql-type="sql_type_name"
check="SQL expression"
default="SQL expression"
read="SQL expression"
write="SQL expression"/>
<formula>SQL expression</formula>
Most of the attributes on column
provide a
means of tailoring the DDL during automatic schema generation. The
read
and write
attributes allow
you to specify custom SQL that Hibernate will use to access the
column's value. For more on this, see the discussion of column read and write
expressions.
The column
and formula
elements can even be combined within the same property or association
mapping to express, for example, exotic join conditions.
<many-to-one name="homeAddress" class="Address"
insert="false" update="false">
<column name="person_id" not-null="true" length="10"/>
<formula>'MAILING'</formula>
</many-to-one>
In relation to the persistence service, Java language-level objects are classified into two groups:
We will revisit both concepts throughout this reference guide.
With the exception of collections, all built-in Hibernate types support null semantics.
The built-in basic mapping types can be roughly categorized into the following:
integer, long, short, float, double, character,
byte, boolean, yes_no, true_false
string
A type mapping from java.lang.String
to
VARCHAR
(or Oracle
VARCHAR2
).
date, time, timestamp
calendar, calendar_date
Type mappings from java.util.Calendar
to SQL types TIMESTAMP
and
DATE
(or equivalent).
big_decimal, big_integer
Type mappings from java.math.BigDecimal
and java.math.BigInteger
to
NUMERIC
(or Oracle
NUMBER
).
locale, timezone, currency
class
binary
text
image
serializable
clob, blob
materialized_clob
materialized_blob
imm_date, imm_time, imm_timestamp, imm_calendar,
imm_calendar_date, imm_serializable, imm_binary
<property name="twoStrings" type="org.hibernate.test.DoubleStringType">
<column name="first_string"/>
<column name="second_string"/>
</property>
Notice the use of <column>
tags to map a
property to multiple columns.
<property name="priority">
<type name="com.mycompany.usertypes.DefaultValueIntegerType">
<param name="default">0</param>
</type>
</property>
<typedef class="com.mycompany.usertypes.DefaultValueIntegerType" name="default_zero">
<param name="default">0</param>
</typedef>
<property name="priority" type="default_zero"/>
<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>
Associations are now specified using entity-name
instead of class
.
Properties marked as generated must additionally be non-insertable and non-updateable. Only versions, timestamps, and simple properties, can be marked as generated.
never
(the default): the given property value is
not generated within the database.
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
: the property value is generated both on
insert and on update.
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.
The first mode is to explicitly list the CREATE and DROP commands in the mapping file:
<hibernate-mapping>
...
<database-object>
<create>CREATE TRIGGER my_trigger ...</create>
<drop>DROP TRIGGER my_trigger</drop>
</database-object>
</hibernate-mapping>
<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>
Copyright © 2004 Red Hat, Inc.