JPA & hibernate annotations

Source: Internet
Author: User

1,@ Entity (name = "entityname ")

Required. The name parameter is optional and corresponds to a table in the database.

2,@ Table (name = "", catalog = "", schema = "")

Optional. It is usually used with @ entity. It can only be labeled in the class definition of an object, indicating the information of the database table corresponding to the object.

Name: (optional) Name of the table. By default, the table name and object name are consistent. You must specify the table name only when they are inconsistent.

Catalog: (optional) specifies the catalog name. The default value is catalog ("").

Schema: Optional. It indicates the schema name. The default value is Schema ("").

3,@ ID

Required

@ ID defines the attribute mapped to the primary key of the database table. Only one attribute of an object can be mapped to the primary key. It is placed before getxxxx.

4,@ Generatedvalue (Strategy = generationtype, generator = "")

Optional

Strategy: indicates the primary key generation policy. There are four types: auto, indentity, sequence, and table. They indicate that the ORM framework is automatically selected,

This parameter is generated based on the database identity field and the database table sequence field to generate a primary key based on an additional table. The default value is auto.

Generator: indicates the name of the primary key generator. This attribute is usually related to the ORM framework. For example, Hibernate can specify the uuid and other primary key generation methods.

Example:

@ ID

@ Generatedvalues (Strategy = strategytype. Sequence)

Public int getpk (){

Return PK;

}

5,@ Basic (fetch = fetchtype, optional = true)

Optional

@ Basic indicates the ing of a simple attribute to fields in the database table. For the getxxxx () method without any annotation, the default value is @ basic.

Fetch: indicates the read policy for this attribute. There are two types: eager and lazy, which respectively indicate master branch crawling and delayed loading. The default value is eager.

Optional: whether the attribute can be null. The default value is true.

Example:

@ Basic (optional = false)

Public String getaddress (){

Return address;

}

6,@ Column

Optional

@ Column describes the detailed definition of this field in the database table, which is very useful for tools that generate the database table structure based on JPA annotations.

Name: indicates the name of the field in the database table. By default, the attribute names are consistent.

Nullable: indicates whether the field can be null. The default value is true.

Unique: indicates whether the field is a unique identifier. The default value is false.

Length: the size of the field. It is only valid for string fields.

Insertable: indicates whether the field should appear in the insetrt statement when the ORM framework performs the insert operation. The default value is true.

Updateable: indicates whether the field should appear in the update statement when the ORM framework performs the update operation. The default value is true. this attribute is useful for fields that cannot be changed once created, for example, the birthday field.

Columndefinition: indicates the actual type of the field in the database. generally, the ORM framework can automatically determine the type of fields in the database based on the attribute type, but the date type still cannot determine whether the field type in the database is date, time or timestamp. in addition, the default ing type of string is varchar. This attribute is useful if you want to map the string type to the blob or text field type of a specific database.

Example:

@ Column (name = "birth", nullable = "false", columndefinition = "date ")

Public String getbithday (){

Return birthday;

}

7,@ Transient

Optional

@ Transient indicates that this attribute is not a ing of fields in the database table. The ORM framework ignores this attribute.

If an attribute is not a field ing of a database table, you must mark it as @ transient. Otherwise, the ORM framework uses its annotation as @ basic by default.

Example:

// Calculate the age attribute based on birth

@ Transient

Public int getage (){

Return getyear (new date ()-getyear (birth );

}

8,@ Manytoone (fetch = fetchtype, cascade = cascadetype)

Optional

@ Manytoone indicates a multi-to-one ing. The annotation attribute is usually the foreign key of the database table.

Optional: whether to allow the field to be null. This attribute should be determined based on the foreign key constraints of the database table. The default value is true.

Fetch: indicates the capture policy. The default value is fetchtype. Eager.

Cascade: indicates the default cascade operation policy, which can be specified as a combination of all, persist, merge, refresh, and remove. The default cascade operation is

Targetentity: indicates the object type associated with this attribute. This attribute does not need to be specified. The ORM framework automatically determines targetentity Based on the attribute type.

Example:

// The order and user are in a manytoone relationship.

// Defined in the order class

@ Manytoone ()

@ Joincolumn (name = "user ")

Public user getuser (){

Return user;

}

9,@ Joincolumn

Optional

@ Joincolumn and @ column are similar. The description is not a simple field, but an associated field, for example, describing a field of @ manytoone.

Name: name of the field. Because @ joincolumn describes an associated field, such as manytoone, the default name is determined by the object associated with it.

For example, if the object order has a user attribute to associate with the object user, the Order user attribute is a foreign key,

The default name is the Object User Name + underline + the primary key name of the Object User

Example:

See @ manytoone

10,@ Onetoetype (fetch = fetchtype, cascade = cascadetype)

Optional

@ Onetoworkflow describes a one-to-many association. This attribute should be of the collective type and has no actual fields in the database.

Fetch: indicates the capture policy. The default value is fetchtype. Lazy, because multiple associated objects do not need to be read from the database in advance to the memory.

Cascade: indicates a cascade operation policy. It is very important for the onetoworkflow type association. Generally, when the object is updated or deleted, its associated entities should also be updated or deleted.

For example, if the relationship between the Object User and order is onetoworkflow, the object order associated with the object user should also be deleted when the object user is deleted.

Example:

@ Onetyade (cascade = All)

Public list getorders (){

Return orders;

}

11,@ Onetoone (fetch = fetchtype, cascade = cascadetype)

Optional

@ Onetoone describes a one-to-one association.

Fetch: indicates the capture policy. The default value is fetchtype. Lazy.

Cascade: indicates the cascade operation policy.

Example:

@ Onetoone (fetch = fetchtype. Lazy)

Public blog getblog (){

Return blog;

}

12,@ Manytoyun

Optional

@ Manytomany describe a many-to-many Association. There are two one-to-many associations on the many-to-many Association. However, in the manytomany description, the intermediate table is automatically processed by the ORM framework.

Targetentity: The full name of another object class associated with multiple-to-multiple pairs, for example, package. Book. Class.

Mappedby: name of the corresponding set attribute of another object class associated with multiple to multiple objects.

Example:

The user entity represents the user, and the book entity represents the book. To describe the user's favorite books, you can establish a manytomany association between the user and the book.

@ Entity

Public class user {

Private list books;

@ Manytoty (targetentity = package. Book. Class)

Public list getbooks (){

Return books;

}

Public void setbooks (list books ){

This. Books = books;

}

}

@ Entity

Public class book {

Private List users;

@ Manytoty (targetentity = package. Users. Class, mappedby = "books ")

Public list getusers (){

Return users;

}

Public void setusers (List users ){

This. Users = users;

}

}

The attributes associated with the two entities must be marked as @ manytoty and the targetentity attribute must be specified for each other,

Note that the @ manytomany Annotation with only one object must specify the mappedby attribute.

13. @ transactionattribute

Transaction Management Service

The most useful Container service may be the transaction management service. When an application fails or encounters an exception, it ensures the integrity of the database. You can simply declare its transaction attributes for a pojo method. In this way, the container can run this method in the appropriate context. The most common transaction is defined on the Session Bean method. All database operations in the method are committed only when the method Exits normally. If the method throws an uncaptured exception, transaction Management rolls back all changes.

@TransactionattributeAnnotation is used to define a method that requires transactions. For example:

@Transactionattribute(Transactionattributetype. required)

Public void insertproduct (string name, float price, Boolean error ){

...

...

}

It can have the following parameters:

A. required: The method is executed in a transaction. If the called method is already in a transaction, use this transaction. Otherwise, a new transaction will be created.

B. Mandatory: The method must be executed in a transaction, that is, the called method must already have a transaction; otherwise, a new error is thrown ).

C. requiresnew: The method is executed in a new transaction. If the called method is already in a transaction, the old transaction is paused.

D. Supports: this transaction is used if the method is called in a transaction. Otherwise, no transaction is used.

E. not_supported: if a method is called in a transaction, an error is thrown)

If no parameter is specified ,@TransactionattributeNote: use required as the default parameter.

14. @ persistencecontexttype

Persistencecontexttype. extended. By default, entitymanagers uses the persistencecontexttype of transaction to create the object. This means that the entity can be managed only when active transactions are processed in the process. Once the transaction processing ends, the entity is managed with the entity.ProgramSo that we can discard it. Extended context type indicates that this detachment will not occur, even if the entity is still hosted after the transaction is processed. This means that you do not need to worry about whether the collection is suspended, because the Entity Management program can be used to complete the necessary retrieval operations. When we want to maintain and update/merge entities, or delete entities from the database, we still need to obtain entitytransaction. For example, we want to save a new application entity:

Public void saveapplication (application ){
Entitytransaction Tx = em. gettransaction ();
TX. Begin ();
Em. persist ();
TX. Commit ();
}

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.