Table of Contents
The reference contains a description of many Hibernate annotations.
If you want to find out supported attributes you may have a look into the source code. In Eclipse you can press CTRL (alias STRG) and click on a class name to display the attached source code. The first time you make this, you have to define where the source code of the class can be found.
Below you can find the source code for the javax.persistence.Table annotation.
You can download the source code for Hibernate annotations at http://www.hibernate.org or use the Maven repository of JBoss. https://repository.jboss.org/nexus/index.html
/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the license at * https://glassfish.dev.java.net/public/CDDLv1.0.html or * glassfish/bootstrap/legal/CDDLv1.0.txt. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * Header Notice in each file and include the License file * at glassfish/bootstrap/legal/CDDLv1.0.txt. * If applicable, add the following below the CDDL Header, * with the fields enclosed by brackets [] replaced by * you own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. */ package javax.persistence; import java.lang.annotation.Target; import java.lang.annotation.Retention; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Target(TYPE) @Retention(RUNTIME) public @interface Table { String name() default ""; String catalog() default ""; String schema() default ""; UniqueConstraint[] uniqueConstraints() default {}; }
@javax.persistence.Entity
Specifies that a class is used by Hibernate as entity
Sample.
@Entity public class Tiger implements Serializable {
@org.hibernate.annotations.Entity
Hibernate extension, must be used in addition to @javax.persistence.Entity
@javax.persistence.Table
Optional, specifies database table a class is mapped.
@org.hibernate.annotations.Table
Hibernate extension to EJB 3, generates indexes, when generating tables. Can be used with the annotations @javax.persistence.Table and @javax.persistence.SecondaryTable
@org.hibernate.annotations.Index
Hibernate extension to EJB 3, specifies an index
Sample.
@Entity() @javax.persistence.Table(name = "tableName", uniqueConstraints = { @UniqueConstraint(columnNames = { "unique_column" }) }) @org.hibernate.annotations.Table(appliesTo = "tableName", indexes = { @Index(name = "forestidx", columnNames = { "indexedcolumn" }) }) public class Garden implements Serializable {
@javax.persistence.SecondaryTable
Map one bean to two tables. You specify for a column, that it belongs to the secondary tables (→ @Column(table=”secondaryTable”)
@javax.persistence.UniqueConstraint
Specifies a unique key constraint. This information is used when Hibernate generates tables.
Source code for examples can be found in the project mapping-examples-annotation package de.laliluna.primarykey.
@javax.persistence.Id
Specifies that an attribute belongs to the primary key. Is applied to all primary key attributes.
@javax.persistence.GeneratedValue
Specifies that the value is generated by a sequence, increment, …
Sample.
@Entity public class Cheetah implements Serializable { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; @Entity public class Tiger implements Serializable { @Id @TableGenerator(name = "puma_gen", table="primary_keys") @GeneratedValue(strategy = GenerationType.TABLE, generator = "puma_gen") private Integer id;
@javax.persistence.IdClass
Specifies a composite primary key, i.e. a key consisting of multiple columns
Sample.
@IdClass(SpottedTurtleId.class) public class SpottedTurtle implements Serializable { @Id private String location; @Id private String favoriteSalad;
@javax.persistence.EmbeddedId
Specifies a composite primary key, i.e. a key consisting of multiple columns. As opposed to IdClass the fields are not included in the class, but only in the primary key.
Sample.
@Entity public class BoxTurtle implements Serializable { @EmbeddedId private BoxTurtleId id;
@javax.persistence.SequenceGenerator
Specifies a generator which can be referenced from @GeneratedValue annotation. It is a HiLo algorithm using a database sequence.
Sample.
@Entity @SequenceGenerator(name = "puma_seq", sequenceName = "puma_id_seq") public class Puma implements Serializable {
@javax.persistence.TableGenerator
Specifies a generator which can be referenced from @GeneratedValue annotation. It is a HiLo algorithm using a database table.
Sample.
@Id @TableGenerator(name = "puma_gen", table="primary_keys") @GeneratedValue(strategy = GenerationType.TABLE, generator = "puma_gen") private Integer id;
@org.hibernate.annotations.GenericGenerator
Hibernate specific generator. It references the id strategies of Hibernate Specifies a generator which can be referenced from @GeneratedValue annotation.
Sample.
@Id @GenericGenerator(name = "aName", strategy = "seqhilo", parameters = { @Parameter(name = "max_lo", value = "5") }) @GeneratedValue(generator = "aName") private Integer id;
Tip: Often you do not need an annotation for your columns. By default all columns are mapped and the column name is the field name. Specify an annotation, if you have a special column (date, enum,…) or if the defaults do not suit your needs.
@javax.persistence.Column
Can be used to specify details for a column.
@javax.persistence.Transient
Specifies that a column is not mapped to a database column.
Sample.
@Transient private String transientField;
@javax.persistence.Basic
Optional, specifies that a field is mapped. By default all columns are mapped.
@javax.persistence.Lob
Specifies that a column is a large object type. Depending on the Java type a CLOB (character large object) or a BLOB (binary large object) is used. Depending on the database version and driver this might not work out of the box. See chapter about Lob Mapping Chapter 10, Lob with Oracle and PostgreSQL
@javax.persistence.Temporal
Precisely defines a date, time or timestamp column
Sample.
@Temporal(value=TemporalType.DATE) private Date dateField;
@javax.persistence.Enumerated
Specifies an enum field. value = EnumType.STRING:: Can be one of the following values: EnumType.STRING or EnumType.ORDINAL STRING let Hibernate create a char column, holding the enum type as character, for example JUNGLE for ForestType.JUNGLE. ORDINAL let Hibernate create an integer column, holding an integer value for each enum type. The first enum type is 0, the second 1, The ORDINAL approach might be a problem, if later you want to insert enum types.
Sample.
public enum ForestType {JUNGLE, FOREST, NORDIC} @Enumerated(EnumType.STRING) private ForestType forestType;
@javax.persistence.Version
Specifies a version column to implement an optimistic locking strategy (see Fehler: Referenz nicht gefunden) Can be applied to the following types int, Integer, short, Short, long, Long, Timestamp. Use only one version column per class. Version column should be in the primary table (→ secondaryTable) Do not update the version column yourself. In some databases a timestamp might be not precisely enough, if your system is fast. Therefore I prefer to use int or long columns.
Sample.
@Version private Long version;
@javax.persistence.AttributeOverride
Overwrites the column definition from a mapped super class or an embedded object.
Sample.
de.laliluna.component.simple.Sheep @Embedded @AttributeOverride(name = "color", column = @Column(name = "pullover_column")) private Pullover pullover;
@javax.persistence.AttributeOverrides Overwrites multiple column definition from a mapped super class or an embedded object. value={@AttributeOverride(…), @AttributeOverride(…)}:: Array of @AttributeOverride
Sample.
@AttributeOverrides({@AttributeOverride(name = "color", column = @Column(name = "pullover_column"))})
@org.hibernate.annotations.AccessType
Specifies how Hibernate sets values. Hibernate can use a set method (property) or reflection to set the private field directly (field). By default, Hibernate verifies where the id is annotated. If the @Id annotation is in front of the field than field based access is assumed. If the annotation is in front of the get method then property based access is used. This annotation can be used in front of a class, a field or a property.
Sample.
@AccessType(value="field") public class Turtle implements Serializable {
@org.hibernate.annotations.Formula
Can be used to get a formula calculated by the database. The column is of course read only.
Sample.
@Formula("10 * id + 5") public Integer formula;
@org.hibernate.annotations.Type Can be used to specify the type being used, instead of Hibernate let select it, based on the Java type or other annotation. You need it in rare cases. Type can be used to specify a Custom type. See TypeDefs for a sample. type=”nameOfTheType”,:: a name of type defined in a @TypeDef or a class parameters = { @Parameter(name = "paramName", value = "theValue") }:: array of parameters. Each parameter has a name and a value.
Sample.
@Type(type = "org.hibernate.type.BinaryType") private byte imageAsBytea[];
@org.hibernate.annotations.TypeDefs
Can be used to define a global name for a type. This is useful, if you work with custom types. value = { @TypeDef(name = "keyType", typeClass = KeyType.class) }:: array of @TypeDef
Sample.
import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; ...... snip ...... @TypeDefs(value = { @TypeDef(name = "keyType", typeClass = KeyType.class) }) @Entity public class YogaClub implements Serializable { @Type(type = "keyType") private String name;
@org.hibernate.annotations.TypeDef
Sample see @TypeDefs
@org.hibernate.annotations.Parameter
Is used together with other annotations, to specify parameters. @TypeDef uses it to pass parameters to custom types. name = "x",:: name of the parameter value = "y":: value of the parameter
@javax.persistence.OneToOne
Defines a one to one relation. Sample: de.laliluna.relation.one2one
Sample.
import javax.persistence.JoinColumn; import javax.persistence.OneToOne; ...... snip ......... @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "invoice_id") private Invoice1 invoice;
@javax.persistence.OneToMany
Specifies a one to many relation. Sample: de.laliluna.relation.one2many
Sample.
@OneToMany @JoinColumn(name="club_id", nullable=false) private Set<JavaClubMember1> members = new HashSet<JavaClubMember1>();
@javax.persistence.ManyToOne
Specifies a one to many relation. Used with the class being the many side of the relation. Sample: de.laliluna.relation.one2many
Sample.
@ManyToOne @JoinColumn(name = "club_id", nullable = false) private JavaClub3 club;
@javax.persistence.ManyToMany
Specifies a many to many relation. Sample: de.laliluna.relation.many2many
Sample.
@ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "concert_visitor_2", joinColumns = { @JoinColumn(name = "concert_id") }, inverseJoinColumns = { @JoinColumn(name = "visitor_id") }) private List<Visitor2> visitors = new ArrayList<Visitor2>();
@javax.persistence.JoinColumn
Used for relation mapping, specifies how tables are joined. Most values are guessed by Hibernate. Sample: de.laliluna.relation…
Sample.
@ManyToOne @JoinColumn(name = "club_id", nullable = false) private JavaClub3 club;
@javax.persistence.JoinColumns
Is used to join classes with composite primary keys. Sample: de.laliluna.component.joincolumns
Sample.
@OneToOne @JoinColumns({ @JoinColumn(name="articleGroup", referencedColumnName="articleGroup"), @JoinColumn(name="articleNumber", referencedColumnName="articleNumber") }) private ElbowRest elbowRest;
@javax.persistence.JoinTable
Used to join a relation with a separate table. Sample: de.laliluna.component.one2many and many2many
Sample.
@ManyToOne @JoinTable(name = "club_member", joinColumns = { @JoinColumn(name = "member_id") }, inverseJoinColumns = { @JoinColumn(name = "club_id") }) private JavaClub4 club;
@javax.persistence.PrimaryKeyJoinColumn
Defines how a table is joined to another table. Sample: de.laliluna.relation.one2one
Sample.
@OneToOne(cascade = CascadeType.ALL,optional=false) @PrimaryKeyJoinColumn private Order3 order;
@javax.persistence.PrimaryKeyJoinColumns
Specifies how a table is joined. Can be used, if you have a composite id.
See the PrimaryKeyJoinColumn sample in de.laliluna.relation.one2one and the composite sample de.laliluna.component.joincolumns to get an impression, when this is used.
@javax.persistence.Embedded
Specifies that another class is embedded in this class. The fields of the embedded class can be mapped to the same table.
Hint: In a newer EJB implementation the Embedded annotation has an array of @AttributeOverride. Hibernate might adopt this as well. example:
Sample (de.laliluna.component.simple.Sheep).
@Embedded @AttributeOverrides({@AttributeOverride(name = "color", column = @Column(name = "pullover_column"))}) private Pullover pullover;
@javax.persistence.ElementCollection()
Maps a collection of components.
Sample (de.laliluna.component.collection1, de.laliluna.component.collection2).
@ElementCollection() @JoinTable(name="pizza_ingredients", joinColumns = @JoinColumn(name="pizza_id")) private Set<Ingredient> ingredients = new HashSet<Ingredient>();
@org.hibernate.annotations.CollectionOfElements
Is now deprecated. Use @javax.persistence.ElementCollection() instead.
@javax.persistence.Embeddable Specifies that this class can be embedded into other classes.
@org.hibernate.annotations.Parent
Can be used in an embedded class, if you need a reference to the parent.
Sample.
import org.hibernate.annotations.Parent; @Embeddable public class DeliveryAddress implements Serializable { @Parent private PizzaClient client;
@javax.persistence.Inheritance
Specifies an inheritance mapping, ie. an inheritance structure of classes is mapped to 1 or more tables. strategy = InheritanceType.SINGLE_TABLE:: Specifies how the inheritance structure is mapped SINGLE_TABLE = All columns from parent and derived classes in the same table. TABLE_PER_CLASS = One table per parent or derived class. The derived tables have the columns from the parent class as well. JOINED = One table per parent or derived class. The parent table holds the data of common columns.
Sample (de.laliluna.inheritance.*).
@Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "plant_type", discriminatorType = DiscriminatorType.STRING) public class Plant implements Serializable { @Entity public class Flower extends Plant {
@javax.persistence.DiscriminatorColumn
Is used with the inheritance type InheritanceType.SINGLE_TABLE. As all classes are stored in one table we need a column which defines what kind of class a row belongs to.
Sample (de.laliluna.inheritance.singletable.*).
@DiscriminatorColumn(name = "plant_type", discriminatorType = DiscriminatorType.STRING, columnDefinition="varchar(31)", length=31)
@javax.persistence.DiscriminatorValue
Optional, can be used with the inheritance type InheritanceType.SINGLE_TABLE, default: class name
Sample.
@Entity @DiscriminatorValue("Flower") public class Flower extends Plant {
@javax.persistence.MappedSuperclass
Specifies an inheritance mapping, where the parent class is not mapped itself. example: de.laliluna.inheritance.mappedsuperclass.*
Sample.
@MappedSuperclass public class MusicBand implements Serializable { ....... @Entity @SequenceGenerator(name = "musicband_seq", sequenceName = "musicband_id_seq") public class SoftrockGroup extends MusicBand{ ......
@javax.persistence.NamedQueries
Defines multiple named queries. See example below.
@javax.persistence.NamedQuery
Defines a query which can be reused at various places. Provides a performance advantage to building queries every time. example: de.laliluna.other.namedquery.*
Sample.
@NamedQueries({ @NamedQuery(name = "bookQuery", query = "from ComputerBook b where b.id > :minId and b.name = :name", hints = { @QueryHint(name = "org.hibernate.readOnly", value = "false"), @QueryHint(name = "org.hibernate.timeout", value = "5000")}) })
Usage.
List<ComputerBook> list = session.getNamedQuery("bookQuery") .setString("name", "Hibernate") .setInteger("minId",10) .list();
@org.hibernate.annotations.NamedQueries
Defines multiple named queries. See example below. The related chapter explains the difference to @javax.persistence.NamedQueries.
@org.hibernate.annotations.NamedQuery
Defines a query which can be reused at various places. Provides a performance advantage to building queries every time. example: de.laliluna.other.namedquery.*
Sample.
@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "bookQuery", query = "from ComputerBook b where b.id > :minId and b.name = :name", flushMode = FlushModeType.AUTO, cacheable = true, cacheRegion = "", fetchSize = 20, timeout = 5000, comment = "A comment", cacheMode = CacheModeType.NORMAL, readOnly = true)})
Usage.
List<ComputerBook> list = session.getNamedQuery("bookQuery") .setString("name", "Hibernate") .setInteger("minId",10) .list();
@javax.persistence.SqlResultSetMappings
Defines multiple result set mappings.
@javax.persistence.SqlResultSetMapping
If you use SQL in a query instead of HQL, you can still create entities as result. A result set mapping tells Hibernate how to transform the SQL result set into entities.
example: de.laliluna.other.namedquery.*
Sample.
@SqlResultSetMappings({ @SqlResultSetMapping(name = "bookReport", entities = {@EntityResult (entityClass = ComputerBook.class, fields = {@FieldResult(name = "id", column = "id"), @FieldResult(name = "name", column = "book_name")})}) })
Usage.
List<ComputerBook> books = session.createSQLQuery ("select id, book_name from computerbook") .setResultSetMapping("bookReport").list();