hibernate annotations reference

50
Hibernate: Annotation Reference The following reference is in the book "Hibernate - The Practice Guide for Developers" by Sebastian contain chicken brothers. An annotation to the entities and tables Annotations for two primary keys Annotations for three columns 4 annotations for relationships Annotations for component 5 A reference annotation - Part 1 This chapter provides a complete overview of all annotations. Short excerpts illustrate the use of source code. If it is an example for download, reference is made to this. The sample code can also be found under "book updates". Reference When I program, I use the source code of Hibernate as helpful support. The annotation source code shows you all the possible attributes and default values. This is almost as good as the reference. In Eclipse you can with the key combination Ctrl (aka Ctrl display) and click on the annotation of the source code. The first time you have to specify where the source is located. The source code for the EJB implementation is not so easy to find. Best use the anonymous Subversion access to the JBoss repository: http://anonsvn.jboss.org/repos/hibernate/trunk/HibernateExt/ejb-api The page http://www.hibernate.org/6.html explains how to configure access. The Hibernate source code you can see from the Hibernate website: http://www.hibernate.org . An annotation to the entities and tables @ Javax.persistence.Entity @ Javax.persistence.Entity ( specifies that a class is a mapped Hibernate entity. name = "EntityName" optionally, the name that is used in queries; Default is the class name ) @ Entity

Upload: rkpunjal

Post on 26-Aug-2014

337 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Hibernate Annotations Reference

Hibernate: Annotation Reference

The following reference is in the book "Hibernate - The Practice Guide for Developers" by Sebastian contain chicken brothers.

An annotation to the entities and tables Annotations for two primary keys Annotations for three columns 4 annotations for relationships Annotations for component 5

A reference annotation - Part 1This chapter provides a complete overview of all annotations. Short excerpts illustrate the use of source code. If it is an example for download, reference is made to this. The sample code can also be found under "book updates".ReferenceWhen I program, I use the source code of Hibernate as helpful support. The annotation source code shows you all the possible attributes and default values. This is almost as good as the reference. In Eclipse you can with the key combination  Ctrl  (aka  Ctrl  display) and click on the annotation of the source code. The first time you have to specify where the source is located.The source code for the EJB implementation is not so easy to find. Best use the anonymous Subversion access to the JBoss repository:http://anonsvn.jboss.org/repos/hibernate/trunk/HibernateExt/ejb-apiThe page http://www.hibernate.org/6.html explains how to configure access. The Hibernate source code you can see from the Hibernate website: http://www.hibernate.org .

An annotation to the entities and tables@ Javax.persistence.Entity

@ Javax.persistence.Entity ( specifies that a class is a mapped Hibernate entity.

name = "EntityName" optionally, the name that is used in queries;Default is the class name

)

@ Entitypublic class Tiger implements Serializable {

@ Org.hibernate.annotations.Entity

@ Org.hibernate.annotations.Entity (

is an extension to the annotation @ javax.persistence.Entity and can only be used in addition, it allows to specify in detail Hibernate-specific parameters for the entity.

Page 2: Hibernate Annotations Reference

mutable = true If the entity is read-only, but can not be changed, should be mutable value falseassign.

dynamic insert = true Update queries for classes are usually created during initialization and update all the columns in the database, even if only one field changes.This is only a problem in a situation exactly:If you mix in a table with columns and columns with short values blobs / CLOBs and frequently change the short columns, which would updatecommand unnecessarily involve the Blob / Clob column and degrade the speed.Solution a: Share your table.

Solution b: Use dynamic-update.If you are dynamic-update use Hibernate dynamically generates an update query that contains only the columns that have changed, too. It is important to know that the generation of the query takes time, because no existing query can be reused. Do not the "normal" tables. For more information, see Section 2.6, "Advanced options".

dynamic update = true The principle is the same as dynamic-update .The difference is that only the column names in the insert query will be used which are not empty.

select before update = false, This setting will degrade performance significantly and should therefore be avoided.

If select-before-update is used, Hibernate checks before each update to a query whether the data has changed. A reasonable scenario would be: You want to avoid an unnecessary update is called by a trigger on the database.

= PolymorphismType.IMPLICIT polymorphism,

This setting determines the behavior of Hibernate in inheritance hierarchies.

Example: class extends flower plant . The query is select from plant .Implicit means that this query, depending on whether a database record a flower or a plant is just an instance of that class returns.

Explicit in this query would be, if there is an instance of the class flower is a class of plantand return the additional fields of flowers just ignore it.

persister = "customPersister" This setting must be changed very infrequently.A persister is responsible for writing the data.You could create such a persister which stores data in LDAP.In Hibernate, download an example in

Page 3: Hibernate Annotations Reference

the testdirectory. Look for the classorg.hibernate.test.legacy.CustomPersister.

optimisticLock = OptimisticLockType.VERSION

Sets the strategy for optimistic lokking fixed. I recommend to change the setting if it is really necessary. A change brings a significant performance hit.

ALL reads the data from the database and check all the columns, whether they have changed. DIRTY also reads out the data validated but only columns that have changed.This allows you to perform concurrent updates on the same record, without there being an exception.More information on Optimistic Locking is provided in Section 5.2.1, "Optimistic locking".

)

@ Entity@ Org.hibernate.annotations.Entity (mutable = true dynamic insert = true dynamic update = true select before update = false, = PolymorphismType.IMPLICIT polymorphism, persister = "customPersister" optimisticLock OptimisticLockType.VERSION =)public class Tiger implements Serializable {

@ Javax.persistence.Table

@ Javax.persistence.Table ( optional, allows to specify the table name to which the class is mapped. The default value is the class or entity name.

name = "tableName" Name of database table

catalog = "catalog name", optional, name of the database catalog (catalogs are not supported by all databases);overrides the default value from the Hibernate configuration

schema = "dbSchemaName" optional, name of the database schema (schemas are not supported by all databases);overrides the default value from the Hibernate configuration

uniqueConstraints = { @ UniqueConstraint ( columnNames = {"database column", "another column"})}

option, causes Hibernate when creating tables a unique key constraint generated;

Page 4: Hibernate Annotations Reference

)

@ Org.hibernate.annotations.Table

@ Org.hibernate.annotations.Table (

Hibernate extension to EJB 3, creates an index when Hibernate generates tables. Can be used with the annotation @ javax.persistence.Tableand @ javax.persistence.SecondaryTable be used.

appliesTo = "tablename" Name of database table

comment = "" Comment on Table

foreignKey = @ ForeignKey (name = "")

Name of the foreign key constraints for relations

fetch = FetchMode.JOIN determines how the secondary table is loaded

inverse = false No insert / update / delete for the secondary table

optional = true = true insert / update into table if at least one secondary attribute is not zero, false = always insert / update

sqlInsert = @ sqlInsert (sql = "") Custom insert command for secondary table

sqlUpdate = @ SQLUpdate (sql = "") Custom update command for secondary table

sqlDelete = @ SQLDelete (sql = "") Custom delete command for secondary table

indexes = {@ Index (name = "forest_idx", columnNames = {"indexedColumn"})}

an array of @ index

)

@ Org.hibernate.annotations.Index

@ Org.hibernate.annotations. Index (

Hibernate EJB 3 extension to define an index

name = "forestidx" Name of index

columnNames = {"colA", "colB"} Database columns that are included in the index

)

@ Entity ()@ Javax.persistence.Table (name = "tableName"uniqueConstraints = {@ UniqueConstraint (columnNames =

Page 5: Hibernate Annotations Reference

{"unique_column"})})@ Org.hibernate.annotations.Table (appliesTo = "tablename"indexes = {@ Index (name = "forestidx", columnNames = {"indexedcolumn"})})Garden implements Serializable {public class

@ Javax.persistence.SecondaryTable

@ Javax.persistence. Secondary Table (

allows to map certain attributes of a class to a second table;set for each attribute must be that in thesecondary table to dump: @ Column (table = "secondary table")Example in Java Packagede.laliluna.other.diverse

name = "tableName" Required field defines the name of the table

catalog = "catalog name", optional, name of the database catalog (catalogs are not supported by all databases);overrides the default value from the Hibernate configuration

schema = "dbSchemaName" optional, name of the database schema (schemas are not supported by all databases);overrides the default value from the Hibernate configuration

pkJoinColumns = {@ PrimaryKeyJoinColumn (name = "id", referencedColumnName = "id", column definition = "int4")}

an array of @ PrimaryKeyJoinColumn that determine how the primary and "mapped" the secondary table.

)

@ Javax.persistence.UniqueConstraint

@ Javax.persistence.UniqueConstraint (

defines a unique key constraint, Hibernate uses this information when creating tables.

columnNames = {"database column name}", "another column"}

Required field, sets the table columns that are included in the constraint

)

@ Org.hibernate.annotations.SQLInsert

custom insert command

sql = "" SQL command

Page 6: Hibernate Annotations Reference

callable = false True = SQL command uses a stored procedure

check = ResultCheckStyle.NONE Examination of the altered lines by the return value of SQL commands, NONE = no check;COUNT = executeUpdate as an SQL statement; PARAM = uses OUT parameters of a stored procedure

@ Org.hibernate.annotations.SQLUpdate

custom update command, see @ sqlInsert

@ Org.hibernate.annotations.SQLDelete

custom delete command, see @ sqlInsert

@ Org.hibernate.annotations.SQLDeleteAll

custom delete command, see @ sqlInsert

@ Immutable org.hibernate.annotations

no saving of entity or attribute changes

Annotations for two primary keysThe source code for the examples can be found in the project DeveloperGuideAnnotation in the Java package de.laliluna.primarykey .

@ Javax.persistence.Id

@ Javax.persistence.Id specifies that an attribute belongs to the primary key, the annotation is written for composite ids from all attributes.

@ Javax.persistence.GeneratedValue

@ Javax.persistence.GeneratedValue (

describes that the ID is generated; there are different strategies to be generated primary key.

strategy = generation type.SEQUENCE,

Default: GenerationType.AUTO (depending on the selected database from a strategy)

Page 7: Hibernate Annotations Reference

GenerationType.SEQUENCE uses a sequence, the default value for the sequence name is hibernate_sequence , Oracle, and other PostgreSql

GenerationType.TABLE stores the last value in a database table (suitable for all databases)

GenerationType.IDENTITY special column type, MS SQL, and other

generator = "generator name" Optional: a reference generator, a generator is allowed to specify more precisely how the ids are generated.Default: This depends on the strategy. For a sequence a generator is used to start a sequence named hibernate_sequence used.

)

@ Entitypublic class implements Serializable {Cheetah @ Id @ GeneratedValue (strategy = GenerationType.AUTO) private Integer id;

@ Entitypublic class Tiger implements Serializable { @ Id Table Generator @ ("puma_gen" name =, table = "primary_keys") @ GeneratedValue (strategy = GenerationType.TABLE, generator = "puma_gen") private Integer id;

@ Javax.persistence.IdClass

@ Javax.persistence.IdClass ( specifies the class that stores a composite primary key.

value = SpottedTurtleId.class Class name of the primary key class

)

@ IdClass (SpottedTurtleId.class)public class implements Serializable {SpottedTurtle @ Id private String location; @ Id private String favorite salad;

@ Javax.persistence.EmbeddedId

Page 8: Hibernate Annotations Reference

@ Javax.persistence.EmbeddedId defines the class that contains the composite primary key, the difference @ IdClass is that the attributes exist only in the primary key class.

@ Entitypublic class implements Serializable {BoxTurtle @ EmbeddedId private BoxTurtleId id;

@ Javax.persistence.SequenceGenerator

@ Javax.persistence.SequenceGenerator (

Id defines a generator driven by the annotation@ GeneratedValue can be referenced, the generator uses a sequence.

name = "generator name", Name of the generator in the annotation @ GeneratedValue can be used

sequenceName = "dbSequenceName" optional, name of the sequence in the database, default hibernate_sequence

initialValue = 1, sets the initial value of the sequence, default: 1

allocationSize = 50 Default value: 50 The sequence generator is not calling for each new record to a database sequence, but increases the sequence around the allocationSize and distributes the numbers.Only when all the numbers are distributed, the sequence is recalled. If you write 50 entries in the database, you save at a allocationSize 50 49 Therefore, the query sequence. The improved performance. The disadvantage is that the assigned IDs during a restart of the application have gaps.

Generators should be global, according to EJB 3 spec, but Hibernate holds at least up to version 3.2 is not in this setting.

)

@ Entity@ SequenceGenerator (name = "puma_seq" sequenceName = "puma_id_seq")public class implements Serializable {Puma

@ Javax.persistence.TableGenerator

Page 9: Hibernate Annotations Reference

@ Javax.persistence. Table Generator (

Id defines a generator driven by the annotation@ GeneratedValue can be referenced, the generator stores the last value in a database table.

name = "generator name", Name of the generator in the annotation @ GeneratedValue can be used

table = "database table", Table in which the next stored value assigned to the Id

catalog = "catalog database" Catalog Database Table (supported by some databases)

schema = "schema name" Database schema of the table (only supported by some databases)

value column name Table column in which is stored next to the assigned value of the Id

pkColumnValue Table column into which a key value is, the value assigned to the next identified; Default: Name of the class

initialValue sets the initial value of the id, default: 1

allocationSize Default value: 50 The generator does not increase for each new record the value of the id in the table, but increases the sequence around the allocationSize and distributes the numbers. Only when all the numbers are distributed, the sequence is recalled. If you write 50 entries in the database, you save at aallocation size of 50 so 49 times, increasing the value. The improved performance. The disadvantage is that the assigned IDs during a restart of the application have gaps.Generators should be global, according to EJB 3 spec, but Hibernate holds at least up to version 3.2 is not in this setting.

uniqueConstraints = { @ UniqueConstraint (columnNames = {"Col_a, col_b"})}

optionally generated when you create the table a unique key constraint

)

@ IdTable Generator @ ("puma_gen" name =, table = "primary_keys")@ GeneratedValue (strategy = GenerationType.TABLE, generator = "puma_gen")private Integer id;

@ Org.hibernate.annotations.GenericGenerator

Page 10: Hibernate Annotations Reference

@ Org.hibernate.annotations.Generic Generator (

Hibernate-specific generator of the annotation@ GeneratedValue can be referenced, the generator uses one of the possible in XML-based mapping strategies that have been described in Section 4.4, "Mapping of primary keys"

name = "generator name",

Name of the generator in the annotation @ GeneratedValue can be used

strategy = "seqhilo"

defines the strategy and can have the following values: identity , sequence , seqhilo , guid ,native , select , hilo , assigned , foreign , uuid ,increment ;(Detailed description in Section 4.4, "Mapping of primary keys")

parameters = {@ Parameter (name = "max_lo" value = "5")}

Array of @ parameters; is used to configure the Id strategy

)

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

Annotations for three columnsTips for using default valuesThe beauty of the EJB 3 spec and thus also to annotation is the wise use of default values. You'll often need no annotation, the defaults are sufficient. All attributes are automatically "mapped" as long as you do not @ Transient annotation set. Only for special types, such asdate , enum , annotation is a necessary in any case.

@ Javax.persistence.Column

@ Javax.persistence.Column ( can be used to accurately determine the table column.

name = "full_described_field" Name of the table column

unique = false, If the value of true is set, Hibernate generates when creating the column a unique key constraint.

nullable = true If the value is false is set, Hibernate

Page 11: Hibernate Annotations Reference

generates when creating the column, an emergency-zero constraint.

insertable = true, specifies that the column in an insert command is taken into account.

updatable = true specifies that the column in an updatecommand is taken into account.

= column definition "Varchar (255)",

allows to determine the SQL type of the column.Default: The value is determined using the Java types and the annotation of the dialect of the Hibernate configuration.

table = "TableName2" Table name of a secondary table, if the information is missing, the column belongs automatically to the primary table, see Table @ Secondary

length = 255 Length of the table column, applies only to the Java type StringDefault value: 255

precision = 0, Decimal places, if the attribute is a number, the default value is determined from the dialect in the hibernate configuration.

Scale = 0 Size of the column if the attribute is a number.The default value is determined from the dialect in the hibernate configuration.

)

@ Javax.persistence.Transient

@ Javax.persistence.Transient defines an attribute that is not "mapped" is

@ Transient private String transientField;

@ Javax.persistence.Basic

@ Javax.persistence.Basic ( allowed to set for a single attribute, whether it should be loaded LAZY

fetch = FetchType.EAGER, Default: EAGER, EAGER means that the attribute is immediately loaded when the object is fetched from the database. LAZY invites an attribute only when accessing the field. This is interesting for BLOB and CLOB attributes. A prerequisite for LAZY loading at the attribute level is bytecode instrumentation (see Section 2.5, "Advanced

Page 12: Hibernate Annotations Reference

Options").

optional = true A note for Hibernate if an attribute is zero can be.

)

@ Javax.persistence.Lob

@ Javax.persistence.Lob defined as an attribute of a large object type is, depending on the Java types a CLOB (ischaracter large object ) or a BLOB ( binary large object ) is used; Important information about Oracle's particular Section 2.5.11, "Oracle with praise and PostgreSQL ".

@ Javax.persistence.Temporal

@ Javax.persistence.Temporal ( precisely define a time-related table column (date, time or timestamp)

value = TemporalType.DATE possible values: DATE, TIME, TIMESTAMP, NONE

)

@ Temporal (value = TemporalType.DATE) private Date date field;

@ Javax.persistence.Enumerated

@ Javax.persistence.Enumerated (

describes an attribute as enum types.

value = EnumType.STRING possible values are: EnumType.STRING orEnumType.ORDINALSTRING causes Hibernate a table column of type char generated that contains the enum types as string: ForestType.JUNGLE = column value JUNGLE.ORDINAL causes Hibernate a table column of type integer generated. For each type, a number is stored. In this approach, you can add new types only at the end, otherwise the assignment of numbers to type to get messed up.

)

public enum Type {Forest JUNGLE, FOREST, NORDIC}

Page 13: Hibernate Annotations Reference

@ Enumerated (EnumType.STRING) Private Forest Type forest type;

@ Javax.persistence.Version

@ Javax.persistence.Version defines a version column in the context ofoptimistic locking is used (see Section 2.5.1, "Byte Code Instrumentation").The annotation attributes can be associated with one of the following Java types: int, Integer, short, short, long, long, java.util.Date .You can use only one version column per class and they should not put themselves. Version column must also be in the primary table (seeannotation @ Secondary Table ).I recommend that attributes of type int or longuse. If you change the server time or your server is very fast, it can be with the guyjava.util.Date be trouble.

@ Version private long version;

@ Javax.persistence.AttributeOverride

@ Javax.persistence. Override attributes (

overwrites the column definition of a luxury or an embedded object.

name = "color", Attribute of the class

column = @ Column (name = "pullover_column")

Column definitions, see @ Column annotation

) Example: de.laliluna.component.simple.Sheep

@ Embedded@ Override attributes (name = "color", column = @ Column (name = "pullover_column"))Private sweater sweater;

@ Javax.persistence.AttributeOverrides

@ Javax.persistence. Overrides attributes (

overwrites several column definitions from a superclass or an embedded object.

value = {@ Override attributes (...) @ Override attributes (...)}

Array of attributes @ Override

)

Page 14: Hibernate Annotations Reference

@ Override attributes (attributes {@ Override (name = "color",column = @ Column (name = "pullover_column"))})

@ Org.hibernate.annotations.Formula

@ Org.hibernate.annotations.Formula (

is used by the database a formula to calculate; the attribute can only read from and written.

value = "10 + 5 * table_column" a formula

)

@ Formula ("id + 10 * 5") public String formula;

4 annotations for relationships@ Javax.persistence.OneToOne

@ Javax.persistence.OneToOne ( defines a 1:1 relationship.Example in the packagede.laliluna.relation.one2one

targetEntity = Invoice1.class, defines the other side of the relationship and the information is not usually necessary, since the other side of the relationship between Hibernate will guess from the Java types.

cascade = {} CascadeType.ALL, Array of Cascade Type - see Section 4.5.4, "Cascasding".

fetch = FetchType.EAGER, determines whether the other side of the relationship until the access ( LAZY () or loaded immediately EAGER ) for 1:1 relationships, the default is EAGER .

optional = true If the value is false , Hibernate generates when you create the table, an emergency-zero constraint. If cascading is configured with the setting DELETE ORPHAN, the other class is deleted, if the relationship is disconnected.

mappedBy = "Other Side property" establishes, manages that in a bi-directional relationship, the other side of the relationship.

)

javax.persistence.JoinColumn import;javax.persistence.OneToOne import;

Page 15: Hibernate Annotations Reference

...... snip .........@ OneToOne (cascade = CascadeType.ALL) @ Column (name = "invoice_id") private Invoice1 invoice;

@ Javax.persistence.OneToMany

@ Javax.persistence.OneToMany ( defines a 1-to-many relationship.Example in the packagede.laliluna.relation.one2many

targetEntity = Invoice1.class, defines the other side of the relationship and the information is not usually necessary, since the other side of the relationship between Hibernate will guess from the Java types.

cascade = {} CascadeType.ALL, Array of Cascade Type - see Section 4.5.4, "Cascasding"

fetch = FetchType.LAZY, determines whether the other side of the relationship until the access ( LAZY () or loaded immediately EAGER ), for 1-to-many relationship is the default LAZY .

mappedBy = "Other Side property" establishes, manages that in a bi-directional relationship, the other side of the relationship.

)

@ OneToMany @ Column (name = "club_id", nullable = false) <JavaClubMember1> <JavaClubMember1> private Set members = new ArrayList ();

@ Javax.persistence.ManyToOne

@ Javax.persistence.ManyToOne ( defines an n: 1 relationship.Example in the packagede.laliluna.relation.one2many

targetEntity = Invoice1.class, defines the other side of the relationship and the information is not usually necessary, since the other side of the relationship between Hibernate will guess from the Java types.

cascade = {} CascadeType.ALL, Array of Cascade Type - see Section 4.5.4, "Cascasding"

fetch = FetchType.EAGER, determines whether the other side of the relationship until the access ( LAZY () or loaded immediately EAGER ), for n: 1 relationship, the default is EAGER .

Page 16: Hibernate Annotations Reference

optional = true If the value is false , Hibernate generates when you create the table, an emergency-zero constraint. If cascading is configured with the setting DELETE ORPHAN, the other class is deleted, if the relationship is disconnected.

)

@ ManyToOne @ Column (name = "club_id", nullable = false) JavaClub3 private club;

@ Javax.persistence.ManyToMany

@ Javax.persistence.ManyToMany ( defines an m: n relationship.Example in the packagede.laliluna.relation.many2many

targetEntity = Invoice1.class, defines the other side of the relationship and the information is not usually necessary, since the other side of the relationship between Hibernate will guess from the generic Java types.

cascade = {} CascadeType.ALL, Array of Cascade Type - see Section 4.5.4, "Cascasding"

fetch = FetchType.EAGER, determines whether the other side of the relationship until the access ( LAZY () or loaded immediately EAGER ) for m: n relationships, the default is LAZY .

mappedBy = "Other Side property" establishes, manages that in a bi-directional relationship, the other side of the relationship.

)

@ ManyToMany (cascade = CascadeType.ALL) @ JoinTable (name = "concert_visitor_2" joinColumns = {@ JoinColumn (name = "concert_id")}, inverseJoinColumns = {@ JoinColumn (name = "visitor_id")}) private List <Visitor2> <Visitor2> visitors = new ArrayList ();

Annotations for component 5@ Javax.persistence.Embedded

@ Javax.persistence.Embedded specifies that a class is included as a component and is stored in the same table.

Page 17: Hibernate Annotations Reference

Note: In a recent implementation of the EJB annotation is an array of @ Override attributes. In Hibernate 3.3 this option was not available.Example in the Java packagede.laliluna.component.simple.Sheep

@ Embedded@ Override attributes (attributes {@ Override (name = "color",column = @ Column (name = "pullover_column"))})Private sweater sweater;

@ Org.hibernate.annotations.CollectionOfElements

@ Org.hibernate.annotations.CollectionOfElements (

Hibernate extension to a map , a set or a list of objects to save as a component.

targetElement Address = winter.class,

defines the class of the component, the information is not usually necessary, since the other side of the relationship between Hibernate will guess from the generic Java types.

fetch = FetchType.EAGER determines whether the component only when accessing ( LAZY () or loaded immediatelyEAGER ), default value is LAZY .

) Example in the Java packagede.laliluna.component.collection1 ,de.laliluna.component.collection2

@ CollectionOfElements @ Column (name = "hedgehog_id") Index @ Column (name = "list_index") <WinterAddress> <WinterAddress> private List addresses = new ArrayList ();

@ Javax.persistence.Embeddable

@ Javax.persistence.Embeddable

specifies that a class can be included as a component.Example in the Java packagede.laliluna.component.simple.Sheep

@ Org.hibernate.annotations.Parent

@ Org.hibernate.annotations.Parent

can be used in a component, if an attribute references the superclass.Example in the Java packagede.laliluna.component.collection2.PizzaClie

Page 18: Hibernate Annotations Reference

nt

org.hibernate.annotations.Parent import;@ Embeddablepublic class implements Serializable {DeliveryAddress @ Parent Pizza Private Client client;

Hibernate: Annotation Reference - Part 2

6 annotations for relationship and components 7 annotations for inheritance 8 Other Annotations 9 annotation for named filter

A reference annotation - Part 2This chapter provides a complete overview of all annotations. Short excerpts illustrate the use of source code. If it is an example for download, reference is made to this. The sample code can also be found under "book updates".

6 annotations for relationship and components@ Javax.persistence.JoinColumn

@ Javax.persistence.JoinColumn ( specifies how the tables are linked to a relationship, and all information is optional.Example in the package de.laliluna.relation

name = "club_id" Name of the table column that contains the foreign key

referencedColumnName = "id" Name of the table column that is referenced by foreign key, default value is the primary key

unique = false, If the value is true is, Hibernate generates when you create the table has a unique constraint .

nullable = true If the value is false is, Hibernate generates when you create the table, an emergency-zero constraint .

insertable = true, determines whether the foreign key column in an insert command is written.

Page 19: Hibernate Annotations Reference

updatable = true determines whether the foreign key column in an update command is written.

column definition = "int4" allows the SQL types to define precisely, and usually determines the Hibernate SQL Types using the Java types of the configured dialect.

table = "" If you use a secondary table, you can specify with this attribute that belongs to the foreign key column of this table (see @ Secondary Table ).

)

@ ManyToOne @ Column (name = "club_id", nullable = false) JavaClub3 private club;

@ Javax.persistence.JoinColumns

@ Javax.persistence.JoinColumns ( is used to combine classes with composite primary keys.Example in the Java packagede.laliluna.component.joincolumns

value = {@ JoinColumn} Array of @ JoinColumn

)

@ OneToOne @ JoinColumns ({ @ Column (name = "article group," referencedColumnName = "article group"), @ Column (name = "article number", referencedColumnName = "article number")}) private ElbowRest elbowRest;

@ Javax.persistence.JoinTable

@ Javax.persistence.JoinTable ( is used to store relations in a mapping table.Example in Java package and de.laliluna.component.one2many many2many

name = "club_member" Name of the mapping table

catalog = "" Database catalog of the mapping table (not supported by all databases)

schema = "" Database schema of the mapping table (not supported by all databases)

joinColumns = {@ JoinColumn (name = "member_id")},

Array of @ JoinColumn, defines the foreign key columns for this side of the relationship, you need multiple @ JoinColumn with

Page 20: Hibernate Annotations Reference

composite primary keys.

inverseJoinColumns = {@ JoinColumn (name = "club_id")},

Array of @ JoinColumn, defines the foreign key columns for the other side of the relationship, you need multiple @ JoinColumn with composite primary keys.

uniqueConstraints = {@ UniqueConstraint (columnNames = {"club_id"})}

Array of @ UniqueConstraint, if configured, Hibernate generates unique constraints when creating tables.

)

@ ManyToOne @ JoinTable (name = "club_member" joinColumns = {@ JoinColumn (name = "member_id")}, inverseJoinColumns = {@ JoinColumn (name = "club_id")}) JavaClub4 private club;

@ Javax.persistence.PrimaryKeyJoinColumn

@ Javax.persistence.PrimaryKeyJoinColumn

allows to combine two tables based on the primary key.Example in the Java packagede.laliluna.relation.one2one

name = "id" Name of the table column that contains the foreign key, the default value assumes the value of the id attribute.

referencedColumnName = "id" Name of the table column that contains the primary key, the default value assumes the value of the id attribute.

column definition = "int4" SQL type of the foreign key column, the default value is taken from the Id attribute.

)

@ OneToOne (cascade = CascadeType.ALL, optional = false) @ PrimaryKeyJoinColumn Order3 private order;

@ Javax.persistence.PrimaryKeyJoinColumns

@ Javax.persistence.PrimaryKeyJoinColumns

is used to link tables with composite primary key based on these.

value = {@} PrimaryKeyJoinColumn Array of @ PrimaryKeyJoinColumn

)

There are similar examples in the Java package de.laliluna.relation.one2one and Component

Page 21: Hibernate Annotations Reference

Example de.laliluna.component.joincolumns.

@ Org.hibernate.annotations.IndexColumn

@ Org.hibernate.annotations.Column index (

allows you to build a relationship with an index column.Example in the Java packagede.laliluna.relation.overview

name = "columnName" Name of the database column

base = 0, Number that is the first index entry, default value is 0

nullable = true determines whether the index column zeroshould be; Hibernate generates when creating tables an emergency-zero constraint.

column definition = "int4" Optional SQL type of the foreign key column, the default value is determined from the configured dialect.

)

@ OneToMany (cascade = CascadeType.ALL)@ Column (name = "developer_id", nullable = false)Index @ Column (name = "index list")private List <Computer> <Computer> computers = new ArrayList ();

@ Org.hibernate.annotations.Cascade

@ Org.hibernate.annotations.Cascade ( Extension to java.persistence.Cascade ; allows cascading for each method of the Hibernate session explicitly set.

{ org.hibernate.annotations.CascadeType.SAVE_UPDATE,org.hibernate.annotations.CascadeType.DELETE}

Array oforg.hibernate.annotations.CascadeType ; possible values:NONE - default, no cascadingALL - cascaded to all methods, including those of the Hibernate extension. There is no delete-orphan on.PERSIST - session.persist ()

Page 22: Hibernate Annotations Reference

SAVE_UPDATE - session.saveOrUpdate ()LOCK - session.lock ()MERGE - session.merge ()DELETE - session.delete () . Caution: Read the instructions in Section 4.5.4, "Cascasding" before you accidentally delete your entire database.DELETE_ORPHAN - If the relationship is deleted, while a 1: n relationship erased the N objects, if there is the foreign key field for an emergency-zero constraint.REFRESH - session.refresh ()EVICT - session.evict () deletes an object from the session cacheREPLICATE - session.replicate (..)

)

@ OneToMany (cascade = CascadeType.ALL)@ Cascade (value = org.hibernate.annotations.CascadeType.DELETE_ORPHAN)private Set <team> <team> hobbies = new HashSet ();

@ Org.hibernate.annotations.Fetch

@ Org.hibernate.annotations. Fetch (

specifies how data is loaded a relationship;Example in the Java packagede.laliluna.other.diverse

value = FetchMode.JOIN possible values:SELECT - The data is a select query rechargedSUBSELECT - The data is a select query recharged, this setting is used when a datastream in XML mapping is used.JOIN - The relationship of the data are loaded together with the primary class. This setting

Page 23: Hibernate Annotations Reference

forces you Eager-loading.

)

@ OneToMany@ JoinColumn@ Fetch (value = FetchMode.JOIN)private List <Tulip> <Tulip> noBlueTulips = new ArrayList ();

@ Javax.persistence.MapKey

@ Javax.persistence.MapKey ( allowed a 1-to-many relationship in ajava.util.Map to store, as in the Java packagede.laliluna.other.mapkeyNote that this form of mapping is a bit unstable.If you mappedBy not use, do not specify a database schema, since it is ignored.

name = "isoCode" Name of an attribute of the other class, as a key in the java.util.Map to be used. Default value is the attribute id.

)

@ OneToMany (mappedBy = "beach")@ Mapkey (name = "isoCode")private Map Country> countries = new HashMap <String, Country> ();

@ Org.hibernate.annotations.MapKey

@ Org.hibernate.annotations.Mapkey (

allowed a 1-to-many relationship in ajava.util.Map to store, but the difference with preceding version, is that no existing attribute of the target class is used as the key. The key of java.util.Map is stored in a separate database column of the mapping table.Example in the Java packagede.laliluna.other.mapkey

columns = {@ Column (name = "otherIsoCode")},

an array of columns that contain the key

targetElement = Country.class the target class of the relationship; particulars of the class is optional and is recognized by Hibernate when using Generics automatically.

)

@ OneToMany@ JoinTable (name = "beach_other_country")@ Org.hibernate.annotations.MapKey (columns =

Page 24: Hibernate Annotations Reference

{@ Column (name = "otherIsoCode")}, element = target Country.class)private Map Country> other countries = new HashMap <String, Country> ();

@ Org.hibernate.NotFound

@ Org.hibernate.NotFound ( If a foreign key column refers to a nonexistent record, is usually thrown an exception. You can configure a relationship so that the missing data is simply ignored.

action = NotFoundAction.IGNORE The default behavior is EXCEPTION and not have to be configured. IGNORE means that no exception is thrown.

)

@ OneToOne (cascade = CascadeType.ALL)@ JoinColumn@ NotFound (action = NotFoundAction.IGNORE)private Head Gardener head gardener;

@ Org.hibernate.annotations.OnDelete

@ Org.hibernate.annotations.OnDelete (

If the annotation with the setting CASCADE is used when generating Hibernate generates tables of a foreign key constraint with the setting on delete cascade . Hibernate will assume that the database passes the deletion.The main advantage is speed of annotation.Example in the Java packagede.laliluna.other.diverse

action = OnDeleteAction.CASCADE possible values: CASCADE NO_ACTION

)

@ OneToOne (cascade = CascadeType.ALL)@ JoinColumn@ OnDelete (action = OnDeleteAction.CASCADE)private Head Gardener head gardener;

@ Javax.persistence.OrderBy

@ Javax.persistence.OrderBy ( sorted in a 1: n relationship, the entries for attributes. If you have an indexed list ( @ index column ), you should instead use the annotation @ org.hibernate.annotations.OrderBy use.Example in the Java packagede.laliluna.other.diverse

Page 25: Hibernate Annotations Reference

value = "attribute-name, other attribute "

a comma-separated list of attributes, optionally with an indication of asc / desc

)

@ OneToMany@ JoinColumn@ Javax.persistence.OrderBy (value = "name desc, id asc")private List <Tulip> <Tulip> tulips = new ArrayList ();

@ Org.hibernate.annotations.OrderBy

@ Org.hibernate.annotations.OrderBy (

sorted in a 1: n relationship, the entries for attributes. Use this annotation when an indexed list ( @ Column index used).Example in the Java packagede.laliluna.other.diverse

clause = "name desc" a SQL collation or the part after the order bywould stand, and it uses the column names instead of attribute names.

)

@ OneToMany@ JoinColumn@ OrderBy (clause = "name desc")private List <Tulip> <Tulip> tulips = new ArrayList ();

@ Org.hibernate.annotations.Where

@ Org.hibernate.annotations. Where (

The example filters all, allows to group the elements of a relationship Tulip out whose column deleted the value false is.Example in the Java packagede.laliluna.other.diverse

clause = 'deleted = false " an SQL WHERE condition

)

@ OneToMany@ JoinColumn@ Where (clause = "deleted = false")private List <Tulip> <Tulip> tulips = new ArrayList ();

@ Org.hibernate.annotations.BatchSize

@ Org.hibernate.annotations. Batch size (

Determines how many connections are loaded in one go. The value overrides the default from the Hibernate configuration in hibernate.cfg.xml. In our example, the

Page 26: Hibernate Annotations Reference

class English Garden , a 1-to-many relationship to class . Tulip If we have a list of class English Garden iterate and see the tulips are at a batch size of 2 is always loaded for the current and the next garden, the tulips. So you save 50% of the database queries.Example in the Java packagede.laliluna.other.diverse

size = 2

)

@ OneToMany@ JoinColumn@ Batch size (size = 2)private List <Tulip> <Tulip> tulips = new ArrayList ();

@ Org.hibernate.annotations.LazyCollection

@ Org.hibernate.annotations.LazyCollection (

When the data is relationships with Lazy Loading initialized when the data or methods ofcollection , such as size or contains access.To access size and contains , it is not necessary to the collection to initialize.Hibernate allows the setting EXTRA avoid the initialization. This saves on large collectionsvery much time.Example in the Java packagede.laliluna.other.diverse

value = LazyCollectionOption.EXTRA possible values:EXTRA = lazy loading, no initialization while accessing size or contains .TRUE = lazy loading, initialization, when accessing the collection.FALSE = Eager-loading

)

@ OneToMany@ JoinColumn@ LazyCollection (value = LazyCollectionOption.EXTRA)private List <Tulip> <Tulip> noBlueTulips = new ArrayList ();

@ Org.hibernate.annotations.LazyToOne

@ allows the lazy loading

Page 27: Hibernate Annotations Reference

Org.hibernate.annotations.LazyToOne (

for OneToOne andManyToOne precise control.Example in the Java packagede.laliluna.other.diverse

value = LazyToOneOption.NO_PROXY possible values:NO_PROXY = lazy loading without using a proxy; requires bytecode instrumentation (see Section 2.5, "Advanced Options"). Without instrumentation is automatically PROXY used.PROXY = proxy with lazy loading, initialization, when accessing the collection. This option does not work in my experience.FALSE = Eager-loading

)

@ LazyToOne (value = LazyToOneOption.NO_PROXY)@ OneToOne (cascade = CascadeType.ALL)@ Column (name = "invoice_id")private Invoice2 invoice;

7 annotations for inheritance@ Javax.persistence.Inheritance

@ Javax.persistence.Inheritance ( defines a class as a superclass of an inheritance hierarchy, the inheritance hierarchy can be stored in one or more tables.

strategy = InheritanceType.SINGLE_TABLE

defines the strategy for the mapping:SINGLE_TABLE = All columns of the upper and lower classes are stored in a table.TABLE_PER_CLASS = The superclass and each subclass has its own table. Inherited columns are included in all tables.JOINED = The superclass and each subclass has its own table. Inherited columns in the table are only the upper class included.

) Example in the Java packagede.laliluna.inheritance. *

@ Entity@ Inheritance (strategy = InheritanceType.SINGLE_TABLE)@ DiscriminatorColumn (name = "plant_type" discriminatorType

Page 28: Hibernate Annotations Reference

DiscriminatorType.STRING =)public class implements Serializable {Plant@ Entitypublic class Flower extends Plant {

@ Javax.persistence. DiscriminatorColumn

@ Javax.persistence.DiscriminatorColumn (

is the inheritance strategyInheritanceType.SINGLE_TABLE used, since all classes are stored in a table, one column is needed that describes what type of class is the entry.

name = "plant_type" Column name of the discriminator column

discriminatorType = DiscriminatorType.STRING,

determines how the discriminator value is stored; STRING stores the class name.Possible values: STRING, CHAR, INTEGER

column definition = "varchar (31)",

optional SQL type of the discriminator column, the default value is measured by thediscriminatorType taken from the configured dialect.

length = 20 Length of the column, default value 31

) Example in the Java packagede.laliluna.inheritance.singletable. *

@ DiscriminatorColumn (name = "plant_type" discriminatorType = DiscriminatorType.STRING, column definition = "varchar (31)", length = 31)

@ Javax.persistence. DiscriminatorValue

@ Javax.persistence.DiscriminatorValue (

optional, with the inheritance strategyInheritanceType.SINGLE_TABLE used, specifies what value for a class in thediscriminator column is written, default value: class name

value = "Flower" a unique name

)

@ Entity@ DiscriminatorValue ("Flower")public class Flower extends Plant {

@ Javax.persistence.MappedSuperclass

@ Javax.persistence.MappedSupercla

defines the upper class of an inheritance hierarchy in which they are not themselves

Page 29: Hibernate Annotations Reference

ss stored or used, and the subclasses of course, save the inherited attributes.Example in the Java packagede.laliluna.inheritance.mappedsuperclass. *

@ MappedSuperclasspublic class implements Serializable {Music Volume .......@ Entity@ SequenceGenerator (name = "musicband_seq" sequenceName = "musicband_id_seq")public class Group extends Soft Rock Music Band {......

@ Org.hibernate.annotations.DiscriminatorFormula

@ Org.hibernate.annotations.DiscriminatorFormula (

Alternative to the annotation @ DiscriminatorColumn; uses a SQL statement to determine the types of classes.

value = "case when name like '% R' then 0 when name like 'G%' then 1 else 2 end"

an SQL snippet that determines the type of class

)

@ DiscriminatorFormula (value ="Case when name like '% R' then 0 when name like 'G%' then 1 else 2 end")

8 Other Annotations@ Org.hibernate.annotations. Access Type

@ Org.hibernate.annotations.Access Type (

determines if Hibernate sets the value of an attribute using the Set method or directly viaReflection accesses the private attributes.Accordingly, the annotations must be before the getters are respectively prior to the attributes. If the annotation is not used, Hibernate will look for the @ Id annotation. If this attribute is before, property used, this stands in front of a getter method is field used as the access method.The annotation can insert it in front of the class, but also against individual attributes.

value = "field" Possible values: Field property

)

Page 30: Hibernate Annotations Reference

@ Access (value = "field")public class implements Serializable {Turtle

@ Org.hibernate.annotations.Type

@ Org.hibernate.annotations. Type (

allowed to specify the SQL types, it is usually sufficient to determine if the Hibernate types using the configured dialect. The specification is needed at most for some databases for LOB fields or if you use a user-defined types (example: see @ TypeDefs) .

type = "nameOfTheType"

parameters = {@ Parameter (name = "paramName" value = "theValue")}

Array of @ parameter to describe the type

)

@ Type (type = "org.hibernate.type.BinaryType") private byte imageAsBytea [];

@ Org.hibernate.annotations.TypeDefs

@ Org.hibernate.annotations.TypeDefs (

allows to define a globally valid name for a user-defined types.Example project DeveloperGuideAnnotation , Java package: de.laliluna.other.usertype

value = {@ typedef (name = "keyType", type = class KeyType.class)}

Array of @ typedef

)

org.hibernate.annotations.Type import;org.hibernate.annotations.TypeDef import;org.hibernate.annotations.TypeDefs import;...... snip ......@ TypeDefs (value = {@ typedef (name = "keyType", type = class KeyType.class)})@ Entitypublic class Yoga Club implements Serializable { @ Type (type = "keyType") private String name;

@ Org.hibernate.annotations.TypeDef

@ Org.hibernate.annotations.Typedef (

allows to define a globally valid name for a user-defined types.Example project DeveloperGuideAnnotation ,

Page 31: Hibernate Annotations Reference

Java package: de.laliluna.other.usertype

name = "keyType" global name

type class = KeyType.class Class of user-defined types

parameters = {@ Parameter (name = "x" value = "y")}

optional parameter (a user-defined type can be parameterized. So you could define a type that depends on a parameter a string converted to lowercase or uppercase).

)

@ see TypeDefs

@ Org.hibernate.annotations.Parameter

@ Org.hibernate.annotations.Parameters (

is used together with other annotations to configure them; @ typedef parameters are, for example, continue to the types defined.

name = "x", Name of the parameter

value = "y" Value of the parameter

)

@ Org.hibernate.annotations.Check

@ Org.hibernate.annotations. Check (

creates a check constraint in the database, our sample allows, for example, no blue tulips.Supposedly you can also write this annotation before a relationship. I can confirm, unfortunately, not that it works.Example in the Java packagede.laliluna.other.diverse

constraints = "name <> 'Blue'" an SQL constraint

)

@ Entity@ Check (constraints = "name <> 'Blue'")Tulip implements Serializable {public class

@ Org.hibernate.annotations.Cache

@ Org.hibernate.annotations. Cache ( defines whether an entity or a relationship of entities to be cached, it is necessary to configure the cache (see Abschhnitt 3.3, "Cache".)

usage = Cache mode, possible values:

Page 32: Hibernate Annotations Reference

CacheConcurrencyStrategy.READ_WRITE,

read-write = read and write of the entity is allowedread only = Entity has read-only his.nonstrict-read-write = read and write, writing is not synchronized.transactional = read and write with the ability to set transaction isolation level.

region = "custom region", instead of the default region, you can create other regions in the cache. The entity is then cached in the region.

include = "all" possible values:all = All values are cachednon-lazy = attributes that are defined as lazy, will not be cached.

)

@ Cache (usage = CacheConcurrencyStrategy.READ_WRITE, region = "custom region" include = "all")public class Developer implements Serializable {......@ Cache (usage = CacheConcurrencyStrategy.READ_WRITE)private List <Computer> <Computer> computers = new ArrayList ();

9 annotation for named filter@ Org.hibernate.annotations.Filters

@ Org.hibernate.annotations.Filter (

defines one or more filters.Example in the Java packagede.laliluna.other.filter

value = {@ Filter (...)} an array of @ filter

)

See example @ filter

@ Org.hibernate.annotations.Filter

@ Org.hibernate.annotations.Filter (

defines a filter that can be enabled in the Hibernate session. A filter can have parameters. The global name and the parameters with the annotation @ org.hibernate.annotations.FilterDef set.

Page 33: Hibernate Annotations Reference

Example in the Java packagede.laliluna.other.filter

name = "region", references the name of the filter, which in the@ FilterDef was set

condition = "lower (name) like lower (: region-name)"

an SQL filter condition, the parameters need to be @ FilterDef be defined

)

@ Entity@ FilterDef (name = "region", parameters = {@ paramdef (name = "region-name", type = "string")})@ Filters ({@ Filter (name = "region", condition = "lower (name) like lower (: region-name)")})public class Desert implements Serializable {Use:session.enableFilter ("region") setParameter ("region-name", "%% West.");. List <Desert> deserts session.createCriteria = (Desert.class) list ();

@ Org.hibernate.annotations.FilterDef

@ Org.hibernate.annotations.FilterDef (

defines the name and the parameters of a filterExample in the Java packagede.laliluna.other.filter

name = "region", Name of the filter

default condition = "" an SQL filter condition that serves as a default value if no condition is defined in the filter.

parameters = {@ paramdef (name = "region-name", type = "string")})

an array of @ paramdef

See example @ filter

@ Org.hibernate.annotations.ParamDef

@ Org.hibernate.annotations.Paramdef (

defines a filter that can be enabled in the Hibernate session. A filter can have parameters. The global name and the parameters with the annotation @ org.hibernate.annotations.FilterDef set.Example in the Java packagede.laliluna.other.filter

name = "region-name", With the name of the filter : region name is used in the filter condition

Page 34: Hibernate Annotations Reference

type Hibernate type of the parameter

)

See example @ filter

Hibernate: Annotation Reference - Part 3

10 annotation for HQL queries 11 annotation for SQL Queries

A reference annotation - Part 3This chapter provides a complete overview of all annotations. Short excerpts illustrate the use of source code. If it is an example for download, reference is made to this. The sample code can also be found under "book updates".

10 annotation for HQL queriesA complete example, see the Java package de.laliluna.other.query.

@ Javax.persistence.NamedQueries

@ Javax.persistence. NamedQueries (

is used to define multiple queries that are loaded by name, the annotation can stand in front of a class or source code from a Java package.Example in the Java packagede.laliluna.other.query

{@ NamedQuery (....)} Array of @ NamedQuery

)

NamedQueries @ (@ {NamedQuery (name = "book query", query = "from Book b where b.id computer> : Mini D and b.name =: name ")})

@ Javax.persistence.NamedQuery

@ Javax.persistence.NamedQuery ( defines a query that can be loaded by name.

name = "book query", global name of a query

Page 35: Hibernate Annotations Reference

query = "from Computer Book"), a query in HQL

hints = {@ QueryHint (...)} an array of references for Hibernate, the behavior of this query.

)

@ NamedQuery (name = "book query",query = "from Book b where b.id computer>: MiniD and b.name =: name")}

@ Org.hibernate.annotations.NamedQueries

@ Org.hibernate.annotations.NamedQueries (

is used to define multiple queries that are loaded by name, the annotation is an extension to EJB 3 spec and allows @ NamedQuery to use. The use of the Hibernate extension since the introduction of @ QueryHint but no longer necessary (see below).The annotation can stand before a class or in front of a Java package.Example in the Java packagede.laliluna.other.query

{@ NamedQuery (....)} Array of @ org.hibernate.annotations.NamedQuery

)

@ Org.hibernate.annotations.NamedQueries ({@ Org.hibernate.annotations.NamedQuery (name = "book query",query = "from Book b where b.id computer>: Mini D and b.name =: name ")})

@ Org.hibernate.annotations.NamedQuery

@ Org.hibernate.annotations.NamedQuery (

defines a query that can be downloaded from the name, there are more parameters than for the annotation @ javax.persistence.NamedQuery available. The use of the Hibernate extension since the introduction of @ QueryHint no longer necessary. The only benefit is a clearer code with defined parameters.

name = "book query", global name of a query

query = "from Computer Book"), a query in HQL

flush mode = FlushModeType.AUTO,cacheable = true cache region = "Region Name" fetchSize = 20,timeout =

possible parameters:read only = on false data are loaded only readable.cache region = name of a cache region (see

Page 36: Hibernate Annotations Reference

5000, comment = "A comment", Cache mode = CacheModeType.NORMAL, read only = true

Section 3.3, "cache")timeout = timeout in milliseconds of the queryfetchSize = When iterating through a large result set, you can load the data into batches in order to reduce memory consumption.fetchSize determines how many rows will be charged per batch.flush mode = sets the flush mode type set of the query, see possible values classorg.hibernate. Flush Mode Typecache mode = determines whether the Abfrache can be cached (see Section 3.3, "cache"); values see org.hibernate. Cache Mode Typecomment = query adds a comment

)

@ Org.hibernate.annotations.NamedQuery (name = "book query", query = "from Book b where b.id computer>: MiniD and b.name =: name", flush mode = FlushModeType.AUTO, cacheable = false, cache region = "Region Name" fetchSize = 20, timeout = 5000, comment = "A comment", Cache mode = CacheModeType.NORMAL, readonly = true)

@ Javax.persistence.QueryHint

@ Javax.persistence.QueryHint (

name = "org.hibernate.readOnly" possible values:org.hibernate.readOnly = If true, are invited to read data only.org.hibernate.cacheRegion = name of a cache region (see Section 3.3, "cache")org.hibernate.timeout = query timeout in millisecondsorg.hibernate.fetchSize = When iterating through a large result set, you can load the data into batches in order to reduce memory consumption. fetchSize determines how many rows will be charged per batch.org.hibernate.flushMode = sets the flush mode of the query; possible values see Classorg.hibernate.FlushModeorg.hibernate.cacheMode = determines whether the query can be cached (see Section 3.3, "Cache").org.hibernate.comment = adds the query to a

Page 37: Hibernate Annotations Reference

comment.

value = "false" Values depend on the type of notice and best seen on the corresponding classes. Example:org.hibernate.cacheMode - Classorg.hibernate.CacheModeorg.hibernate.flushMode - Classorg.hibernate.FlushMode

)

@ QueryHint (name = "org.hibernate.readOnly" value = "false")

11 annotation for SQL QueriesAn example of SQL queries, see the Java packagede.laliluna.other.query .

@ Javax.persistence.NamedNativeQueries

@ Javax.persistence.NamedNativeQueries (

is used to define multiple SQL queries that are loaded by name, the annotation can stand before a class or in front of a Java package.

({@ NamedNativeQuery (...)} Array of @ NamedNativeQuery

)

@ SqlResultSetMappings ({@ SqlResultSetMapping (name = "book report", entities = {@ EntityResult (entityClass = ComputerBook.class, fields = {@ Result Field (name = "id", column = "id"), Field @ Result (name = "name", column = "name")})})}) NamedNativeQueries @ (@ {NamedNativeQuery (name = "reportSql" query = "select id, name from annotation.computerbook" resultClass = ComputerBook.class, resultSetMapping = "book report")})

@ Javax.persistence.NamedNativeQuery

@ Javax.persistence.NamedNativeQuery (

defines an SQL query that can be loaded by name.

name = "reportSql" global name of a query

query = "select id, name from annotation.computerbook"

a query in SQL

hints = {@ QueryHint (...)} an array of references for Hibernate, the

Page 38: Hibernate Annotations Reference

behavior of this query.

resultClass = ComputerBook.class, Type of class that is delivered as a result

resultSetMapping = "book report" references a mapping of SQL-result columns to the attributes of the class (see @ SqlResultSetMappings)

)

@ NamedNativeQuery (name = "reportSql" query = "select id, name from annotation.computerbook" resultClass = ComputerBook.class, resultSetMapping = "book report")})

@ Javax.persistence.SqlResultSetMappings

@ Javax.persistence.SqlResultSetMappings (

is used to define multiple mappings of SQL queries on class attributes

{@ SqlResultSetMapping (...)} Array of @ SqlResultSetMapping

)

@ SqlResultSetMappings ({@ SqlResultSetMapping (name = "book report" entities = {@ EntityResult (entityClass = ComputerBook.class, fields = {@ Result Field (name = "id", column = "id"), Field @ Result (name = "name", column = "name")})})})

@ Javax.persistence.SqlResultSetMapping

@ Javax.persistence.SqlResultSetMapping (

defines the mapping of SQL queries on class attributes or columns in a SQL query result, though they represent no entity (scalar values).You can also mix the two things (see the array of values in HQL).

name = "book report" global name of a mapping

entities = {@ EntityResult (...) Array of @ EntityResult; is used when the result of a query are entities, determines which entities are included, and associates with @ Result Field , the SQL columns to the attributes.

, Columns = {@ Column Result ()} Array of @ Column result is used when the result of the query does not entities, but scalar values. A query with a scalar result, for example, the number of rows with the name xy (in the example source code).

Page 39: Hibernate Annotations Reference

)

@ SqlResultSetMapping (name = "book report" entities = {@ EntityResult (entityClass = ComputerBook.class, fields = {@ Result Field (name = "id", column = "id"), Field @ Result (name = "name", column = "name")})})

@ Javax.persistence.EntityResult

@ Javax.persistence. EntityResult (

sets are mapped to an entity such as the SQL columns to the attributes of the class.

(EntityClass = ComputerBook.class, Class of Entity

fields = {@ Result Field (...) Array of Field @ Result; is used to assign a column attributes Entites.

, DiscriminatorColumn = "columnName"

allows an inheritance hierarchy withdiscriminator column to map to the query result.

)

@ EntityResult (entityClass = ComputerBook.class,fields = {@ Result Field (name = "id", column = "id"),Field @ Result (name = "name", column = "name")})

@ Javax.persistence.FieldResult

@ Javax.persistence.FieldResult ( attribute assigns a class to a SQL column.

name = "id" Name of the attribute

column = "id" Name of the SQL column

)

Field @ Result (name = "id", column = "id")

@ Javax.persistence.ColumnResult

@ Javax.persistence.ColumnResult ( defines a scalar result column.

name = "count_group" Name of the SQL column

)

Result @ Column (name = "count_group")