Appendix A. Appendix

Table of Contents

Annotation Reference
Entity and table annotation
Primary key annotations
Column annotations
Special
Relation annotations
Join column annotations
Components
Inheritance
Queries
Not yet described

Annotation Reference

The reference contains a description of many Hibernate annotations.

Default values of 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 {};
}

Entity and table annotation

@javax.persistence.Entity

Specifies that a class is used by Hibernate as entity

name="EntityName"
Optional, name which can be used in queries, default: class name

Sample. 

@Entity
public class Tiger implements Serializable {

@org.hibernate.annotations.Entity

Hibernate extension, must be used in addition to @javax.persistence.Entity

mutable=true,
if false then the entity is treated as read only, default is true
dynamicInsert=false,
if true then only changed columns will be included in the insert statement. The default is false which is better in most cases as the same prepared statement can be reused all the time.
dynamicUpdate=false,
if true then only changed columns will be included in the update statement. The default is false which is better in most cases as the same prepared statement can be reused all the time.
selectBeforeUpdate=false,
Makes a select and compares the data and will only create an update if the data was changed. Default is false.
polymorphism=PolymorphismType.IMPLICIT,
Selects of parent classes in a inheritance hierarchy can return all entities as instance of the queried class (explicit polymorphism) or as instance of the class it should actually be (implicit polymorphism)
persister="",
Default is "". It allows to modify how the data is stored. It is rarely changed but allows for example to store data in JNDI.
optimisticLock= OptimisticLockType.VERSION
Defines how optimistic locking works. Default is a version column but you can compare all columns (OptimisticLockType.ALL) or just the changed columns (OptimisticLockType.DIRTY) to verify if a row has been updated by someone else.

@javax.persistence.Table

Optional, specifies database table a class is mapped.

name = "tableName",
Optional, name of the database table to which the class is mapped, default: class name
catalog = "catalogName",
Optional, name of the database catalogue (only supported by some databases), default: name, defined in the Hibernate configuration
schema = "dbSchemaName",
Optional, name of database schema (only supported by some databases), default: name, defined in the Hibernate configuration
uniqueConstraints = { @UniqueConstraint(columnNames = { "databaseColumn}", “anotherColumn” }) }
Optional, no influence on Hibernate but on the table generation. It will generate unique key constraints.

@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

appliesTo = "tableName",
database table name
indexes = { @Index(name = "forest_idx", columnNames = {"indexedColumn"}) }
one or more indexes

@org.hibernate.annotations.Index

Hibernate extension to EJB 3, specifies an index

name = "forestidx",
Name of the index
columnNames = {"colA","colB"}
Database column names which are included in the 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”)

name = "tableName",
Required, specifies the name of the database table to which the class is mapped.
catalog = "catalogName",
Optional, specifies the catalog catalogue name (only support by some databases), default: name, defined in the Hibernate configuration..
schema = "dbSchemaName",
Optional, specifies the schema name (only support by some databases), default: name, defined in the Hibernate configuration.
pkJoinColumns = { @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id", columnDefinition = "int4") }
One or more PrimaryKeyJoinColumn to define how the tables are mapped.

@javax.persistence.UniqueConstraint

Specifies a unique key constraint. This information is used when Hibernate generates tables.

columnNames = { "databaseColumnName}", “anotherColumn” }
Required, specifies the table column names.

Primary key annotations

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, …

strategy=GenerationType.SEQUENCE,
Default: GenerationType.AUTO (selects generator depending on the database GenerationType.SEQUENCE uses a sequence, default name is hibernate_seq, (Oracle PostgreSql and other) GenerationType.TABLE uses a table to store the latest primary key value (all databases) GenerationType.IDENTITY special column table (MS SQL and other)
generator="generatorName"
Optional: References the generator which can be defined in front of the class or field. Default: Name of the default provider, depends on the generation type (e.g. SEQUENCE uses hibernate_seq as sequence.

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

value=SpottedTurtleId.class
the class which is used for the primary key. It must have a column for each @Id column.

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.

name=”generatorName”,
name, which can be referenced from @GeneratedValue
sequenceName=”dbSequenceName”,
optional, database sequence name, default: hibernate_id_seq
initialValue=50,
when the sequence is generated, defines the initial value, default: 1
allocationSize=1
default: 50, The SequenceGenerator is in fact a HiLo sequence generator. A value is retrieved from a sequence, then the generator creates an allocationSize number of unique primary keys. With an allocation size of 5 you can create 5 entities and need only to retrieve one time the sequence value. Generators should be global but Hibernate has an implementation bug here. If you share a sequence across a number of generators, the generated id will frequently jump by the allocation size instead of incrementing. Either use one generator per class or set the allocationSize to 1. If you insert lots of entities, for example during an import job, an allocationSize of 50, will save 49 sequence database queries per 50 inserts. This could improve performance by nearly 100 %.

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.

name=”generatorName”,
name, which can be referenced from @GeneratedValue
table=”databaseTable”,
table, which stores the last primary key value
catalog=”databaseCatalog”,
database catalog, qualifier for table (only supported by some databases)
schema=”schemaName”,
database schema, qualifier for table (only supported by some databases)
pkColumnName=""
primary key column name identifying the generator of a class, default: sequence_name
valueColumnName=""
column holding the next hi value, default: sequence_name
pkColumnValue
primary key value, default: name of the class initialValue: default: 0 allocationSize: default: 50
uniqueConstraints={@UniqueConstraint(columnNames={"col_A, col_B"})}
Optional, no influence on Hibernate but on the table generation. It will generate unique key constraints.

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.

name=”generatorName”,
name, which can be referenced from @GeneratedValue
strategy = "seqhilo",
The strategies are explained in chapter . Can be any of the following identity, sequence, seqhilo, guid, native, select, hilo, assigned, foreign, uuid, increment
parameters = { @Parameter(name = "max_lo", value = "5") }
array of parameters. Each parameter has a name and a value.

Sample. 

@Id
@GenericGenerator(name = "aName", strategy = "seqhilo",
   parameters = { @Parameter(name = "max_lo", value = "5") })
@GeneratedValue(generator = "aName")
private Integer id;

Column annotations

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.

name="full_described_field",
database column name
unique=false,
If set to true, generates a unique key constraint, if the table is generated.
nullable=true,
If set to false, generates a not null constraint.
insertable=true,
Specifies if Hibernate can insert an object into the database.
updatable=true,
Specifies if Hibernate can update an object in the database.
columnDefinition="varchar(255)",
Can be used to explicitly define an SQL type for the column. Default: value as defined by the dialect in the Hibernate configuration.
table="tableName2",
Table name of a secondary table. If not specified the column belongs to the primary table.
length=255,
Length of the column (applies to String values only), Default: 255
precision=0,
Decimal precision, if column is a decimal value. Default: value as defined by the dialect in the Hibernate configuration.
scale=0
Decimal scale, if column is a decimal value. Default: value as defined by the dialect in the Hibernate configuration. )

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

fetch=FetchType.EAGER,
Specifies if a field is loaded when the object is loaded (EAGER) or when the field is accessed (LAZY). Field based Lazy loading does only work with Bytecode instrumentation. If not enabled than the LAZY will not be recognized. Default: FetchType.EAGER
optional=true
A hint, if this field can be null. )

@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

value=TemporalType.DATE
Can be any of the following types: DATE, TIME, TIMESTAMP, NONE

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.

name = "color",
field of the class
column = @Column(name = "pullover_column")
a column definition → see @Column

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

Special

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

value=”field”
Can be field or 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.

value="10 * table_column + 5"
A formula being calculated in the DB.

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

name=”keyType”,
Global name of the type, to be used when properties are defined
typeClass = KeyType.class
Class of the user type
parameters = { @Parameter(name = "x", value = "y") }
Optional parameters (A custom type can be parametrized. Imagine a type providing lower case, upper case Strings, depending on a parameters.)

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

Relation annotations

@javax.persistence.OneToOne

Defines a one to one relation. Sample: de.laliluna.relation.one2one

targetEntity = Invoice1.class,
Normally guessed from the Class. Specifies the other side of the relation.
cascade = {CascadeType.ALL},
Array of cascadeTypes -see chapter explaining Cascasde
fetch=FetchType.EAGER,
Specifies if the other class is loaded, if this class is loaded. For one2one the default is EAGER. You can set it to LAZY as well.
optional=true,
Defines a not null contraint, if set to false.
mappedBy="otherSideProperty"
In a bi-directional relation, specifies that the other side manages the relation.

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

targetEntity = Invoice1.class,
Can be guessed, if you use generics. Specifies the other side of the relation.
cascade = {CascadeType.ALL},
Array of cascadeTypes -see chapter explaining cascasding
fetch=FetchType.LAZY,
Specifies if the other class is loaded, if this class is loaded. For one2many the default is LAZY. You can set it to EAGER as well.
mappedBy="otherSideProperty"
In a bi-directional relation, specifies that the other side manages the relation.

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

targetEntity = Invoice1.class,
Normally guessed from the Class. Specifies the other side of the relation.
cascade = {CascadeType.ALL},
Array of cascadeTypes -see chapter explaining Cascasde
fetch=FetchType.EAGER,
Specifies if the other class is loaded, if this class is loaded. For one2one the default is EAGER. You can set it to LAZY as well.
optional=true,
Defines a not null contraint, if set to false. Default is true

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

targetEntity = Invoice1.class,
Can be guessed, if you use generics. Specifies the other side of the relation.
cascade = {CascadeType.ALL},
Array of cascadeTypes -see chapter explaining Cascasde
fetch=FetchType.EAGER,
Specifies if the related objects are loaded, if this class is loaded. For many2many the default is LAZY. You can set it to EAGER as well.
mappedBy="otherSideProperty"
In a bi-directional relation, specifies that the other side manages the relation.

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

Join column annotations

@javax.persistence.JoinColumn

Used for relation mapping, specifies how tables are joined. Most values are guessed by Hibernate. Sample: de.laliluna.relation…

name = "club_id",
Column name storing the foreign key
referencedColumnName="id",
The name of the column which is referenced by the foreign key. By default the primary key column is referenced but you can specify another column as well.
unique=false,
Used, when Hibernate generates tables. This will generate a unique key constraint.
nullable = true,
Used, when Hibernate generates tables. This will generate a not null constraint.
insertable=true,
Specify if this column can be inserted, if an object is saved.
updatable=true,
Specify if this column can be updated, if an object is saved.
columnDefinition="int4",
The SQL type of the foreign key column.
table=""
If you use a secondary table, you can specify in which table your foreign key is placed. → see secondary table.

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

value = {@JoinColumn}
array of @JoinColumn

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

name = "club_member",
database table name used for joining
catalog="",
database catalog (only supported by some databases)
schema="",
database schema (only supported by some databases)
joinColumns = { @JoinColumn(name = "member_id") },
Array of joinColumn. Defines the JoinColumns on this side of the relation. You need multiple columns for composite ids.
inverseJoinColumns = { @JoinColumn(name = "club_id") },
Array of joinColumn. Defines the JoinColumns on the other side of the relation. You need multiple columns for composite ids.
uniqueConstraints={@UniqueConstraint(columnNames={"club_id"})}
If you let Hibernate create tables, this information is used to create unique key constraints.

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

name = "id",
Name of the column used in the secondary table. (Foreign key) Default is the name of the primary key column.
referencedColumnName = "id",
Name of the column used in the primary table. (Primary key). Default values are taken from the primary key definition.
columnDefinition = "int4"
SQL type of the foreign key column. Default values are taken from the primary key column.

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.

value={@PrimaryKeyJoinColumn}
array of @PrimaryKeyJoinColumn

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.

Components

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

targetClass
Target class, optional, normally taken from generic declaration
fetch=FetchType.EAGER
Specifies how the data is fetched (EAGER | LAZY), default: LAZY

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;

Inheritance

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

name = "plant_type",
Database column name
discriminatorType = DiscriminatorType.STRING,
Specifies the approach how the discriminator is stored. STRING gives an easily readable representation. Can be any of STRING, CHAR, INTEGER
columnDefinition="varchar(31)",
optional, database column type, normally taken from the discriminatorType
length=20
length of database column, default: 31

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

value=”Flower”
unique name specifying a derived class

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

Queries

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

Not yet described

@javax.persistence.MapKey @javax.persistence.OrderBy @org.hibernate.NotFound @OnDelete @javax.persistence.OrderBy cache DiscriminatorFormula LazyToOne, LazyCollection, Fetch Batchsize, check, where indexcolumn, mapkey

Filter

Filter, FilterDef