Hibernate Annotation Method Usage Summary

Source: Internet
Author: User

1. Class-level annotations

@Entity Mapping entity classes

@Table map number of database tables

@Entity (name= "TableName")-Must be, annotations declare a class as an entity bean.

Property:

Name-optional, corresponding to a table in the database. If the table name is the same as the entity class name, you can omit it.

@Table (name= "", catalog= "", Schema= "")-optional, usually used in conjunction with @entity, can only be labeled at the class definition of the entity, representing the information for the database table of the entity.

Property:

Name-optional, indicates the name of the table, by default, the table name and entity name are the same, only need to specify the table name in case of inconsistency

Catalog-optional, which represents the catalog name, which defaults to catalog ("").

Schema-optional, representing the schema name, which defaults to schema ("").

2. Attribute level annotations

To generate a primary key @Id map

@Version Defining optimistic Locks

@Column the columns of the mapping table

@Transient Defining Transient Properties

2.1 Notes related to the primary key

@Id-a property that is mapped to the primary key of a database table must be defined, and an entity can have only one attribute mapped to the primary key, before Getxxxx ().

@GeneratedValue (strategy=generationtype,generator= "")-optional, which defines the primary key generation strategy.

Property:

Strategy-Represents the primary key generation policy, with the following values:

Generationtype.auto-Automatically select based on the underlying database (default), or autogrow if the database supports auto-grow types.

Generationtype.indentity-built according to the identity field of the database, supports DB2, MySQL, MS, SQL Server, Sybase, and Hyp The identity type primary key for the Eranoicsql database.

Generationtype.sequence-use SEQUENCE to determine the value of the primary key, suitable for Oracle, DB2 and other supporting SEQUENCE database, generally combined with @sequen Cegenerator use.

(Oracle does not have auto-grow type, only with sequence)

Generationtype.table-uses the specified table to determine the primary key value, combined with @tablegenerator.

Such as:

@Id

@TableGenerator (name= "Tab_cat_gen", allocationsize=1)

@GeneratedValue (strategy=generationtype.table)

Generator-Represents the name of the primary key generator, which is usually related to the ORM framework, for example:

Hibernate can specify how to generate primary keys such as UUID

@SequenceGenerator-the annotation declares a database sequence.

Property:
Name-represents the table primary key generation policy name, which is referenced in the "Gernerator" value set in @generatedvalue.
Sequencename-Indicates the name of the database sequence used to generate the policy.
InitialValue-Represents the primary key initial value, which defaults to 0.
Allocationsize-Each time the primary key value increases in size, for example, set to 1, it indicates that a new record is automatically added 1 after each creation, and the default is 50.

Example:

@Id

@GeneratedValues (strategy=strategytype.sequence)

public int getpk () {

return PK;

}

When Hibernate's access type is field, the annotation sounds on the field;

When the access type is property, a comment declaration is made on the getter method.

2.2 Notes related to non-primary keys

@Version-@version annotations can be used in entity beans to add support for optimistic locking

@Basic-the access policy used to declare properties:

@Basic (Fetch=fetchtype.eager) Instant access (default Access Policy)

@Basic (Fetch=fetchtype.lazy) delayed acquisition

@Temporal-Used to define the time precision mapped to the database:

@Temporal (temporaltype=date) Date

@Temporal (Temporaltype=time) time

@Temporal (Temporaltype=timestamp) both

@Column-You can map a property to a column, use that annotation to override the default value, @Column describe the detailed definition of the field in the database table, which is useful for tools that generate database table structures based on JPA annotations.

Property:

Name-optional, which represents the names of the fields in the database table, and the default case property names are the same

Nullable-optional, indicates whether the field is allowed to be null, default is True

Unique-optional, indicates whether the field is a unique identity, false by default

Length-optional, indicates the size of the field, only valid for a field of type String, and the default value is 255.

Insertable-optional, indicating whether the field should appear in the INSETRT statement when the ORM Framework performs an insert operation, which is true by default

Updateable-optional, indicating whether the field should appear in the UPDATE statement when the ORM framework performs an update operation, which is true by default. This property is useful for fields that cannot be changed once created, such as for the Birthday field.

ColumnDefinition-optional, which represents the actual type of the field in the database. Usually the ORM framework can automatically determine the type of a field in a database based on the type of the property, but it is still not possible to determine whether the field type in the database is Date,time or timestamp for the DATE type. In addition, the default mapping type for string is VARCHAR, which is useful if you want to map a string type to a blob or TEXT field type of a particular database.

Example:

@Column (name= "BIRTH", nullable= "false", columndefinition= "DATE")

Public String Getbithday () {

return birthday;

}

@Transient-optional, which indicates that the property is not a mapping to a field in a database table, the ORM framework ignores the property, and if a property is not a field mapping for a database table, it must be marked as @transient, otherwise the ORM framework defaults to its annotation as @Basic

Example:

Calculates the age property based on birth

@Transient

public int getage () {

Return GetYear (New Date ())-getYear (birth);

}

2.3 Default values for no annotation properties

If the property is a single type, it is mapped to @basic,

Otherwise, if the property corresponds to a type that defines the @embeddable annotation, the mapping is @embedded,

Otherwise, if the property corresponds to a type that implements serializable, the property is mapped to @basic and the serialized version of the object is saved in a column.

Otherwise, if the property is of type Java.sql.Clob or JAVA.SQL.BLOB, it acts as @lob and maps to the appropriate lobtype:

3. Mapping Inheritance Relationships

@Inheritance annotations to define the selected policy. This annotation needs to be used on the topmost entity class for each class hierarchy (hierarchy)

4. Mapping Entity Bean Association Relationship 4.1 Some definitions of association mappings

One-to-many: a party has a collection attribute, contains multiple parties, and the parties do not have a reference to a party. User---> Email

One-way many-to-one: multiple parties have a reference, one side does not have a multi-party reference. Paper Category---> Category

Bi-directional one-to-many: there are multiple references on both sides, convenient to query. Class---> Students

Bidirectional many-to-one: Both sides have a multi-reference, convenient query.

One-way many-to-many: an intermediate table is required to maintain two entity tables. Forum---> Articles

One-way: data is unique, and database data is single. Ship---> Sailors

Primary key is the same as one to the other: Use the same primary key, omitting foreign key associations. Customer---> Address

One-way: who manages which side of the relationship is written.

Bidirectional: Generally managed by multiple parties.

@OneToMany (mappedby= "opposite Party")//reverse configuration, the other side management.

4.2 Some common properties of association mappings

Common attributes for @OneToOne, @OneToMany, @ManyToOne, Manytomany:

Fetch-Configures the mode of loading. Value is

Fetch.eager-Load in time, many to one default is Fetch.eager

Fetch.lazy-Lazy load, one-to-many default is Fetch.lazy

Cascade-Sets the cascading method, with the following values:

Cascadetype.persist-Save

Cascadetype.remove-Delete

Cascadetype.merge-Modify

Cascadetype.refresh-Refresh

Cascadetype.all-All

Targetentity-Configure collection property types, such as: @OneToMany (Targetentity=book.class)

@JoinColumn-optional, used to describe an associated field.

@JoinColumn similar to @column, a medium is not a simple field, but an associated field, such as a field that describes a @ManyToOne.

Property:

Name-the names of the fields, because @joincolumn describes an associated field, such as Manytoone, the default name is determined by its associated entity.

For example, the entity order has a user attribute to associate the entity user, and the order's user property is a foreign key.

Its default name is the name of the entity user + underscore + entity user's primary Key name

4.3 One-to-one correlation

@OneToOne – Represents a one-to-one mapping

1. The primary table Class A corresponds to the primary key value from table Class B.
Main Table: @OneToOne (cascade = Cascadetype.all)
@PrimaryKeyJoinColumn
Public B Getb () {

Return b;

}
From table: None

2. The main Table A has a type B from the Table property

Main Table: @OneToOne (cascade = Cascadetype.all)
@JoinColumn (name= "primary table foreign Key")//The Foreign key field in the database is specified here.
Public B Getb () {

return b;

}

From table: None

3. There is one in main Table A from the table property is type B, and at the same time, from table B there is a primary table property is a type a
Main Table: @OneToOne (cascade = Cascadetype.all)
@JoinColumn (name= "primary table foreign Key")//The Foreign key field in the database is specified here.
Public B Getb () {

return b;

}
From table: @OneToOne (Mappedby = "from table properties in the Main Table class")
Public Main Table class get Main Table class () {

Return Main Table Object

}
Note: The @JoinColumn is optional. The default value is from the table variable name + "_" + the primary key from the table (note that this Riga is the primary key.) Instead of the primary key).

4.4 Many-to-one correlation

@ManyToOne-Represents a many-to-one mapping, which is typically a foreign key to a database table.

1. One-way many-to-one: multiple parties have a reference, one side does not have a multi-party reference.

In multiple

@ManyToOne (Targetentity=xxxx.class)//Specify associated objects

@JoinColumn (name= "")//Specify the resulting foreign key field name

2. Bidirectional many-to-one: the configuration is the same as two-way pair.

Example:

Order orders and user users are a manytoone relationship

Defined in the Order class

@ManyToOne ()

@JoinColumn (name= "USER")

Public User GetUser () {

return user;

}

4.5 One-to-many associations

@OneToMany-Describes a one-to-many association, which should be a collection type, with no actual fields in the database.

1. One-way-to-many: one party has a collection attribute, contains multiple parties, and the parties do not have a reference to a party.

@OneToMany use the Join table as a one-to-many association by default

When you add @joincolumn (name= "xxx_id"), the Foreign Key association is used instead of the join table.

2. Bidirectional one-to-many

1) in multiple

@ManyToOne

@JoinColumn (name= "own database foreign key column name")

2) on one side

@OneToMany (mappedby= "Multi-Port Association property name")

@JoinColumn (name= "Each other's database foreign key column name")

4.6 Many-to-many associations

@ManyToMany-optional, describes a many-to-many association.

Property:

Targetentity-The full name of another entity class that represents a many-to-many association, for example: package. Book.class

Mappedby-In the bidirectional correlation, the maintenance right of the relationship is flipped.

1. One-way many-to-many associations:

Add @manytomany annotations to the main control side.

2. Bidirectional many-to-many associations:

The attributes that are related to the two entities must be marked as @manytomany and specify the Targetentity property with each other. @manytomany annotations that have and only one entity need to specify the Mappedby property, which points to the Targetentity collection property name.

Hibernate Annotation Method Usage Summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.