Sie sind auf Seite 1von 40

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 ( name = "EntityName" specifies that a class is a mapped Hibernate entity. optionally, the name that is used in queries; Default is the class name

) @ Entity public class Tiger implements Serializable { @ Org.hibernate.annotations.Entity @ is an extension to the annotation @ Org.hibernate.annotations.Entity javax.persistence.Entity and can only be used in ( addition, it allows to specify in detail Hibernate-specific parameters for the entity.

mutable = true

If the entity is read-only, but can not be changed, should be mutable value falseassign. 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 insert = true

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

select before update = false,

= PolymorphismType.IMPLICIT polymorphism,

This setting determines the behavior of Hibernate in inheritance hierarchies. Example: class extends is select from plant .

flower plant . The query

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 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 of database table optional, name of the database catalog (catalogs are not supported by all databases); overrides the default value from the Hibernate configuration optional, name of the database schema (schemas are not supported by all databases); overrides the default value from the Hibernate configuration option, causes Hibernate when creating tables a unique key constraint generated;

name = "tableName" catalog = "catalog name",

schema = "dbSchemaName"

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

@ 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" comment = "" Name of database table Comment on Table

foreignKey = @ ForeignKey (name = Name of the foreign key constraints for "") relations fetch = FetchMode.JOIN inverse = false optional = true determines how the secondary table is loaded No insert / update / delete for the secondary table

= true insert / update into table if at least one secondary attribute is not zero, false = always insert / update
Custom insert command for secondary table Custom update command for secondary table Custom delete command for secondary table

sqlInsert = @ sqlInsert (sql = "") sqlUpdate = @ SQLUpdate (sql = "") sqlDelete = @ SQLDelete (sql = "") indexes = {@ Index (name = "forest_idx", columnNames = {"indexedColumn"})} ) @ Org.hibernate.annotations.Index @ Org.hibernate.annotations. Index ( name = "forestidx" columnNames = {"colA", "colB"} )

an array of

@ index

Hibernate EJB 3 extension to define an index

Name of index Database columns that are included in the index

@ Entity () @ Javax.persistence.Table (name = "tableName" uniqueConstraints = {@ UniqueConstraint (columnNames = {"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" catalog = "catalog name", Required field defines the name of the table optional, name of the database catalog (catalogs are not supported by all databases); overrides the default value from the Hibernate configuration optional, name of the database schema (schemas are not supported by all databases); overrides the default value from the Hibernate configuration

schema = "dbSchemaName"

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

@ PrimaryKeyJoinColumn that determine


an array of how the primary and "mapped" the secondary table.

@ defines a unique key constraint, Hibernate Javax.persistence.UniqueConstraint 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 = "" callable = false SQL command

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 keys


The 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

@ describes that the ID is generated; there are Javax.persistence.GeneratedValue different strategies to be generated primary key. ( strategy = generation type.SEQUENCE, Default: GenerationType.AUTO (depending on the selected database from a strategy)

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.

) @ Entity public class implements Serializable {Cheetah @ Id @ GeneratedValue (strategy = GenerationType.AUTO) private Integer id; @ Entity public 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 ( value = SpottedTurtleId.class ) @ IdClass (SpottedTurtleId.class) specifies the class that stores a composite primary key. Class name of the primary key class

public class implements Serializable {SpottedTurtle @ Id private String location; @ Id private String favorite salad; @ Javax.persistence.EmbeddedId @ 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.

@ Entity public class implements Serializable {BoxTurtle @ EmbeddedId private BoxTurtleId id; @ Javax.persistence.SequenceGenerator @ Id defines a generator driven by the Javax.persistence.SequenceGenerator 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 sets the initial value of the sequence, default: 1 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.

initialValue = 1, allocationSize = 50

) @ Entity @ SequenceGenerator (name = "puma_seq" sequenceName = "puma_id_seq") public class implements Serializable {Puma @ Javax.persistence.TableGenerator @ 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 of the generator in the annotation @ GeneratedValue can be used Table in which the next stored value assigned to the Id Catalog Database Table (supported by some databases) Database schema of the table (only supported by some databases) Table column in which is stored next to the assigned value of the Id Table column into which a key value is, the value assigned to the next identified; Default: Name of the class sets the initial value of the id, default: 1 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. optionally generated when you create the table a unique key constraint

name = "generator name",

table = "database table", catalog = "catalog database" schema = "schema name" value column name pkColumnValue

initialValue allocationSize

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

) @ Id Table Generator @ ("puma_gen" name =, table = "primary_keys") @ GeneratedValue (strategy = GenerationType.TABLE, generator = "puma_gen") private Integer id; @ Org.hibernate.annotations.GenericGenerator @ Org.hibernate.annotat ions.Generic Generator ( name = "generator name", strategy = "seqhilo" 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 of the generator in the annotation @ used

GeneratedValue can be

defines the strategy and can have the following values: identity , sequence , seqhilo , guid ,native , select , hilo , a ssigned , 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 columns


Tips for using default values The 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 as date , 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" unique = false,

Name of the table column If the value of true is set, Hibernate generates when creating the column a unique key constraint. If the value is false is set, Hibernate generates when creating the column, an emergency-zero constraint. specifies that the column in an insert command is taken into account. specifies that the column in an updatecommand is taken into account. 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 name of a secondary table, if the information is missing, the column belongs automatically to the primary table, see Table

nullable = true

insertable = true,

updatable = true

= column definition "Varchar (255)",

table = "TableName2"

@ Secondary
length = 255 Length of the table column, applies only to the Java type String Default value: 255 precision = 0, Decimal places, if the attribute is a number, the default value is determined from the dialect in the hibernate configuration. Size of the column if the attribute is a number. The default value is determined from the dialect in the hibernate configuration.

Scale = 0

) @ Javax.persistence.Transient @ Javax.persistence.Transient @ Transient private String transientField; @ Javax.persistence.Basic @ Javax.persistence.Basic ( allowed to set for a single attribute, whether it defines an attribute that is not "mapped" is

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 Options"). A note for Hibernate if an attribute is zero can be.

optional = true

) @ 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 ( value = TemporalType.DATE ) @ Temporal (value = TemporalType.DATE) private Date date field; @ Javax.persistence.Enumerated @ describes an attribute as enum types. Javax.persistence.Enumerated ( value = EnumType.STRING possible values are: EnumType.STRING orEnumType.ORDINAL precisely define a time-related table column (date, time or timestamp) possible values: DATE, TIME, TIMESTAMP, NONE

STRING 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} @ 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 ( name = "color", column = @ Column (name = "pullover_column") ) overwrites the column definition of a luxury or an embedded object. Attribute of the class 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 ( value = {@ Override attributes (...) @ Override attributes (...)} ) @ Override attributes (attributes {@ Override (name = "color", column = @ Column (name = "pullover_column"))}) @ Org.hibernate.annotations.Formula @ is used by the database a formula to Org.hibernate.annotations.Formula calculate; the attribute can only read from ( and written. value = "10 + 5 * table_column" ) @ Formula ("id + 10 * 5") public String formula; a formula overwrites several column definitions from a superclass or an embedded object. Array of attributes

@ Override

4 annotations for relationships


@ Javax.persistence.OneToOne @ Javax.persistence.OneToOne ( defines a 1:1 relationship. Example in the packagede.laliluna.relation.one2one 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.

targetEntity = Invoice1.class,

cascade = {} CascadeType.ALL,

Array of Cascade Type - see Section


4.5.4, "Cascasding". determines whether the other side of the relationship until the access ( LAZY () or

fetch = FetchType.EAGER,

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 emergencyzero constraint. If cascading is configured with the setting DELETE ORPHAN, the other class is deleted, if the relationship is disconnected. establishes, manages that in a bi-directional relationship, the other side of the relationship.

mappedBy = "Other Side property" )

javax.persistence.JoinColumn import; javax.persistence.OneToOne import; ...... 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 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.

targetEntity = Invoice1.class,

cascade = {} CascadeType.ALL,

Array of Cascade Type - see Section


4.5.4, "Cascasding" 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 . establishes, manages that in a bi-directional relationship, the other side of the relationship.

fetch = FetchType.LAZY,

mappedBy = "Other Side property" )

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

targetEntity = Invoice1.class,

cascade = {} CascadeType.ALL,

Array of Cascade Type - see Section


4.5.4, "Cascasding" determines whether the other side of the relationship until the access ( LAZY () or loaded immediately EAGER ), for n: 1 relationship, the default is EAGER . If the value is false , Hibernate generates when you create the table, an emergencyzero constraint. If cascading is configured with the setting DELETE ORPHAN, the other class is deleted, if the relationship is disconnected.

fetch = FetchType.EAGER,

optional = true

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

targetEntity = Invoice1.class,

cascade = {} CascadeType.ALL,

Array of Cascade Type - see Section


4.5.4, "Cascasding" determines whether the other side of the relationship until the access ( LAZY () or loaded immediately EAGER ) for m: n

fetch = FetchType.EAGER,

relationships, the default is mappedBy = "Other Side property" )

LAZY .

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. 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.Colle ctionOfElements ( targetElement Address = winter.class, fetch = FetchType.EAGER Hibernate extension to a save as a component.

map , a set or a list of objects to

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. 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 @ can be used in a component, if an attribute references the Org.hibernate.annotations.Paren superclass. t Example in the Java packagede.laliluna.component.collection2.PizzaClien

t
org.hibernate.annotations.Parent import; @ Embeddable public 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 2


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

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 of the table column that contains the foreign key Name of the table column that is referenced by foreign key, default value is the primary key If the value is true is, Hibernate generates when you create the table has a unique constraint . If the value is false is, Hibernate generates when you create the table, an emergencyzero constraint . determines whether the foreign key column in an insert command is written. determines whether the foreign key column in an update command is written. allows the SQL types to define precisely, and usually determines the Hibernate SQL Types using the Java types of the configured dialect. 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 ).

name = "club_id" referencedColumnName = "id"

unique = false,

nullable = true

insertable = true, updatable = true column definition = "int4"

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 of the mapping table Database catalog of the mapping table (not supported by all databases) Database schema of the mapping table (not supported by all databases)

name = "club_member" catalog = "" schema = ""

joinColumns = {@ JoinColumn (name Array of @ JoinColumn, defines the foreign = "member_id")}, key columns for this side of the relationship, you need multiple @ JoinColumn with 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. Array of @ UniqueConstraint, if configured, Hibernate generates unique constraints when creating tables.

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

@ ManyToOne @ JoinTable (name = "club_member" joinColumns = {@ JoinColumn (name = "member_id")}, inverseJoinColumns = {@ JoinColumn (name = "club_id")}) JavaClub4 private club; @ Javax.persistence.PrimaryKeyJoinColumn @ allows to combine two tables based on Javax.persistence.PrimaryKeyJoinColumn 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. Name of the table column that contains the primary key, the default value assumes the value of the id attribute. SQL type of the foreign key column, the default value is taken from the Id attribute.

referencedColumnName = "id"

column definition = "int4"

) @ OneToOne (cascade = CascadeType.ALL, optional = false) @ PrimaryKeyJoinColumn Order3 private order; @ Javax.persistence.PrimaryKeyJoinColumns @ is used to link tables with composite Javax.persistence.PrimaryKeyJoinColumns primary key based on these. value = {@} PrimaryKeyJoinColumn ) There are similar examples in the Java package de.laliluna.relation.one2one and Component 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 of the database column Number that is the first index entry, default value is 0 determines whether the index column zeroshould be; Hibernate generates when creating tables an emergency-zero constraint. Optional SQL type of the foreign key column, the default value is determined from the configured dialect. Array of @ PrimaryKeyJoinColumn

name = "columnName" base = 0, nullable = true

column definition = "int4"

@ 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.Casca de ; allows cascading for each method of the Hibernate session explicitly set.

{ org.hibernate.annotations.CascadeType.SAVE_UPDATE,org.hi Array bernate.annotations.CascadeType.DELETE} oforg.hibernate.annotatio ns.CascadeType ; possible values: NONE - default, no cascading ALL - cascaded to all methods, including those of the Hibernate extension. There is no delete-orphan on. PERSIST session.persist () 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 cache REPLICATE 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 ( value = FetchMode.JOIN specifies how data is loaded a relationship; Example in the Java packagede.laliluna.other.diverse possible values: SELECT - The data is a select query recharged SUBSELECT - 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 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.mapkey Note 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 of an attribute of the other class, as a key in the java.util.Map to be used. Default value is the attribute id.

name = "isoCode"

) @ 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 an array of columns that contain the key the target class of the relationship; particulars of the class is optional and is recognized by Hibernate when using Generics automatically.

columns = {@ Column (name = "otherIsoCode")}, targetElement = Country.class

) @ OneToMany @ JoinTable (name = "beach_other_country") @ Org.hibernate.annotations.MapKey (columns = {@ 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. The default behavior is EXCEPTION and not have to be configured. IGNORE means that no exception is thrown.

action = NotFoundAction.IGNORE

) @ OneToOne (cascade = CascadeType.ALL) @ JoinColumn @ NotFound (action = NotFoundAction.IGNORE) private Head Gardener head gardener; @ Org.hibernate.annotations.OnDelete @ If the annotation with the Org.hibernate.annotations.OnDelete 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 possible values: CASCADE NO_ACTION

action = OnDeleteAction.CASCADE )

@ 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 a comma-separated list of attributes, optionally with an indication of asc / desc

value = "attribute-name, other attribute " )

@ OneToMany @ JoinColumn @ Javax.persistence.OrderBy (value = "name desc, id asc") private List <Tulip> <Tulip> tulips = new ArrayList (); @ Org.hibernate.annotations.OrderBy @ sorted in a 1: n relationship, the entries for Org.hibernate.annotations.OrderBy 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 an SQL WHERE condition

clause = 'deleted = false " )

@ 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 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 @ When the data is relationships with Org.hibernate.annotations.LazyCollection 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 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 DiscriminatorType.STRING =) public class implements Serializable {Plant @ Entity public class Flower extends Plant { @ Javax.persistence. DiscriminatorColumn @ is the inheritance Javax.persistence.DiscriminatorColumn 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" discriminatorType = DiscriminatorType.STRING, Column name of the discriminator column determines how the discriminator value is stored; STRING stores the class name.Possible values: STRING, CHAR, INTEGER optional SQL type of the discriminator column, the default value is measured by thediscriminatorType taken from the configured dialect. Length of the column, default value 31

column definition = "varchar (31)",

length = 20

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

@ DiscriminatorColumn (name = "plant_type" discriminatorType = DiscriminatorType.STRING, column definition = "varchar (31)", length = 31) @ Javax.persistence. DiscriminatorValue @ optional, with the inheritance Javax.persistence.DiscriminatorValue strategyInheritanceType.SINGLE_TABLE used, ( specifies what value for a class in thediscriminator column is written, default value: class name value = "Flower" ) @ Entity @ DiscriminatorValue ("Flower") public class Flower extends Plant { @ Javax.persistence.MappedSuperclass @ defines the upper class of an inheritance hierarchy Javax.persistence.MappedSuperclass in which they are not themselves stored or used, and the subclasses of course, save the inherited attributes. Example in the Java packagede.laliluna.inheritance.mappedsuperclass. * @ MappedSuperclass public 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 @ Alternative to the Org.hibernate.annotations.DiscriminatorFormula annotation @ ( DiscriminatorColumn; uses a SQL statement to determine the types of classes. value = "case when name like '% R' then 0 when an SQL snippet that name like 'G%' then 1 else 2 end" determines the type of class ) a unique name

@ 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. Possible values: Field property

value = "field" )

@ 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 = Array of @ parameter to describe the type "paramName" value = "theValue")} ) @ Type (type = "org.hibernate.type.BinaryType") private byte imageAsBytea []; @ Org.hibernate.annotations.TypeDefs

@ allows to define a globally valid name for a Org.hibernate.annotations.TypeDefs user-defined types. ( Example project DeveloperGuideAnnotation , Java package: de.laliluna.other.usertype value = {@ typedef (name = "keyType", type = class KeyType.class)} ) 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)}) @ Entity public class Yoga Club implements Serializable { @ Type (type = "keyType") private String name; @ Org.hibernate.annotations.TypeDef @ allows to define a globally valid name for a Org.hibernate.annotations.Typedef user-defined types. ( Example project DeveloperGuideAnnotation , Java package: de.laliluna.other.usertype name = "keyType" type class = KeyType.class global name Class of user-defined types Array of @ typedef

parameters = {@ Parameter (name = optional parameter (a user-defined type can "x" value = "y")} 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 @ is used together with other annotations to Org.hibernate.annotations.Parameters configure them; @ typedef parameters ( are, for example, continue to the types defined. name = "x", Name of the parameter

value = "y" ) @ Org.hibernate.annotations.Check @ Org.hibernate.annotations. Check (

Value of the parameter

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 an SQL constraint

constraints = "name <> 'Blue'" )

@ 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: CacheConcurrencyStrategy.READ_WRITE, read-write = read and write of the entity is allowed read 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. possible values: all = All values are cached non-lazy = attributes that are defined as lazy, will not be cached.

include = "all"

) @ 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 ( value = {@ 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. Example in the Java packagede.laliluna.other.filter references the name of the filter, which in the@ FilterDef was set an SQL filter condition, the parameters need to be @ FilterDef be defined defines one or more filters. Example in the Java packagede.laliluna.other.filter an array of @ filter

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

@ 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 @ defines the name and the parameters of a Org.hibernate.annotations.FilterDef filter ( Example in the Java packagede.laliluna.other.filter name = "region", default condition = "" Name of the filter an SQL filter condition that serves as a default value if no condition is defined in the filter. an array of @ paramdef

parameters = {@ paramdef (name = "region-name", type = "string")}) See example @ filter @ Org.hibernate.annotations.ParamDef

@ defines a filter that can be enabled in the Org.hibernate.annotations.Paramdef 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", type ) See example @ filter With the name of the filter : region name is used in the filter condition Hibernate type of the parameter

Hibernate: Annotation Reference - Part 3

10 annotation for HQL queries 11 annotation for SQL Queries

A reference annotation - Part 3


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

10 annotation for HQL queries


A 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 (....)} ) 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 ( name = "book query", query = "from Computer Book"), hints = {@ QueryHint (...)} ) @ NamedQuery (name = "book query", query = "from Book b where b.id computer>: MiniD and b.name =: name")} @ Org.hibernate.annotations.NamedQueries @ is used to define multiple queries that Org.hibernate.annotations.NamedQueries 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. defines a query that can be loaded by name. global name of a query a query in HQL an array of references for Hibernate, the behavior of this query. Array of @ NamedQuery

Example in the Java packagede.laliluna.other.query {@ 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 @ defines a query that can be downloaded from Org.hibernate.annotations.NamedQuery 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", query = "from Computer Book"), flush mode = FlushModeType.AUTO,cacheable true cache region = "Region Name" fetchSize = 20,timeout 5000, comment = "A comment", mode = CacheModeType.NORMAL, only = true = = Cache read global name of a query a query in HQL possible parameters: read only = on false data are loaded only readable. cache region = name of a cache region (see Section 3.3, "cache") timeout = timeout in milliseconds of the query 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. flush mode = sets the flush mode type set of the query, see possible values classorg.hibernate. Flush Mode Type cache mode = determines whether the Abfrache can be cached (see Section 3.3, "cache"); values see org.hibernate. Cache Mode Type comment = query adds a comment Array of @ org.hibernate.annotations.NamedQuery

) @ 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 milliseconds org.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.FlushMode org.hibernate.cacheMode = determines whether the query can be cached (see Section 3.3, "Cache"). org.hibernate.comment = adds the query to a comment. Values depend on the type of notice and best seen on the corresponding classes. Example: org.hibernate.cacheMode Classorg.hibernate.CacheMode org.hibernate.flushMode Classorg.hibernate.FlushMode

value = "false"

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

11 annotation for SQL Queries


An example of SQL queries, see the Java packagede.laliluna.other.query . @ Javax.persistence.NamedNativeQueries

@ is used to define multiple SQL queries that Javax.persistence.NamedNativeQueries are loaded by name, the annotation can ( stand before a class or in front of a Java package. ({@ 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 @ defines an SQL query that can be loaded by Javax.persistence.NamedNativeQuery name. ( name = "reportSql" query = "select id, name from annotation.computerbook" hints = {@ QueryHint (...)} resultClass = ComputerBook.class, resultSetMapping = "book report" global name of a query a query in SQL an array of references for Hibernate, the behavior of this query. Type of class that is delivered as a result references a mapping of SQL-result columns to the attributes of the class (see @ SqlResultSetMappings) Array of @ NamedNativeQuery

) @ NamedNativeQuery (name = "reportSql" query = "select id, name from annotation.computerbook" resultClass = ComputerBook.class, resultSetMapping = "book report")}) @ Javax.persistence.SqlResultSetMappings @ is used to define multiple mappings of Javax.persistence.SqlResultSetMappings 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 @ defines the mapping of SQL queries on Javax.persistence.SqlResultSetMapping 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" entities = {@ EntityResult (...) global name of a mapping 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. 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).

, Columns = {@ Column Result ()}

) @ 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, fields = {@ Result Field (...) Class of Entity 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" column = "id" ) Field @ Result (name = "id", column = "id") @ Javax.persistence.ColumnResult @ Javax.persistence.ColumnResult ( name = "count_group" ) Result @ Column (name = "count_group") defines a scalar result column. Name of the SQL column Name of the attribute Name of the SQL column

Das könnte Ihnen auch gefallen