Spring+hibernate entity class annotations Detailed (non-original) + Cascade attribute value

Source: Internet
Author: User
Tags class definition

@Entity // inheritance policy. Another class inherits this class, so the attributes in this class are applied to another class @Inheritance (strategy = inheritancetype.joined) @Table (name= "Infom_ TestResult ")publicclassextends identity{}

1

@Entity (name= "EntityName")

Have to

name is optional and corresponds to one of the tables in the database

2

@Table (name= "", catalog= "", Schema= "")

optional , usually used in conjunction with @entity, can only be labeled at the class definition of the entity, indicating the database table information for the entity
name: Optional, which represents the name of the table. By default, the table name and entity name are the same, and you 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 ("").

3

@id

Have to
@id defines a property that maps to the primary key of a database table, an entity can have only one attribute mapped to the primary key. Before Getxxxx ().

4

@GeneratedValue (strategy=generationtype,generator= "")

options available
Strategy: Represents the primary key generation strategy, there are auto,indentity,sequence and TABLE 4, respectively, to let the ORM framework automatically select,
Generated based on the identity field of the database, generated from the sequence field of the database table to generate a primary key based on an additional table, default to Auto
Generator: Represents the name of the primary key generator, which is usually related to the ORM framework, for example, hibernate can specify how the primary key is generated, such as the UUID.
Example:

@Id @generatedvalues (Strategy=strategytype.sequence)  Public int getpk () {   return  PK;}

5

@Basic (fetch=fetchtype,optional=true)

options available
@Basic represents a simple property mapping of a field to a database table, and for a getxxxx () method that does not have any callouts, the default is @basic
Fetch: Represents the read policy for this property, there are eager and lazy two, respectively, the main support crawl and lazy load, the default is eager.
Optional: Indicates whether the property is allowed to be null, default is True
Example:

@Basic (optional=false) public String getaddress () {  return  Address;}

6

@Column

Optional
@Column describes the detailed definition of the field in a database table, which is useful for tools that generate database table structures based on JPA annotations.
Name : Represents the name of the field in the database table, the default case property name is the same
nullable : Indicates whether the field is allowed to be null, default is True
Unique : Indicates whether the field is a unique identity and defaults to false
length : Indicates the size of the field and is valid only for fields of type string
Insertable : Indicates whether the field should appear in the INSETRT statement when the ORM Framework performs an insert operation, by default, True
updateable : Indicates that when an ORM framework performs an update operation, Whether the field should appear in the UPDATE statement, by default, is true. This property is useful for fields that cannot be changed once created, such as for birthday fields.
ColumnDefinition : Represents the actual type of the field in the database. Usually ORM frameworks can automatically determine the type of fields in a database based on their property type. However, for date types, it is still not possible to determine whether the field type in the database is Date,time or
TIMESTAMP . In addition, the default mapping type for string is varchar, This property is useful if you want to map a string type to a blob or text field type of a specific database.
Example:

@Column (name= "BIRTH", nullable= "false", columndefinition= "DATE") public String Getbithday () {   return birthday;}

7

@Transient

options available
@Transient indicates that the property is not a mapping to a field in a database table, the ORM framework ignores the property.
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);}

8

@ManyToOne (Fetch=fetchtype,cascade=cascadetype)

options available
@ManyToOne represents a many-to-one mapping, which is typically a foreign key to a database table
Optional: If the field is allowed to be null, the property should be determined by the foreign KEY constraint of the database table, which is true by default
Fetch: Indicates a crawl policy, default is Fetchtype.eager
Cascade: Represents the default cascading action policy, which can be specified as several combinations in All,persist,merge,refresh and remove, with no cascading action by default (see the last Cascade property value)
targetentity: Represents the entity type that the attribute is associated with. This property is not usually specified, and the ORM framework automatically determines targetentity based on the property type.
Example:

// order orders and user users are a manytoone relationship // defined in the Order class @ManyToOne () @JoinColumn (name= "USER")  Public User GetUser () {  return  user;}

9

@JoinColumn

options available
@JoinColumn Similar to @column, a mediator describes not a simple field, but one by one associated fields, such as. Describes a @manytoone field.
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
Example:
See @ManyToOne

10

@OneToMany (Fetch=fetchtype,cascade=cascadetype)

options available
@OneToMany describes a one-to-many association, which should be a collective type, with no actual fields in the database.
Fetch: Represents a crawl policy, which defaults to Fetchtype.lazy, because multiple objects associated often do not have to be pre-read from the database to memory
Cascade: Represents a cascading action policy that is important for an association of onetomany types, usually when the entity is updated or deleted, its associated entities should also be updated or deleted
For example, if the entity user and order are onetomany relationships, the entity user is deleted and its associated entity order should also be deleted
Example:

@OneTyMany (cascade= all) public List getorders () {  return  orders;}
11
@OneToOne (Fetch=fetchtype,cascade=cascadetype)

options available
@OneToOne describe a one-to-one association
Fetch: Indicates a crawl policy, default is Fetchtype.lazy
Cascade: Indicates cascading action policies
Example:

@OneToOne (fetch=fetchtype.lazy) public Blog Getblog () {  return  blog;}

12

@ManyToMany

options available
@ManyToMany describes a many-to-many association. Many-to-many associations are two one-to-many associations, but in the manytomany description, the intermediate table is automatically processed by the ORM framework
targetentity: The full name of another entity class that represents a many-to-many association, for example: package. Book.class
mappedby: The corresponding collection property name of another entity class that represents a many-to-many association
Example:

//user entities represent users, book entities represent books, and in order to describe user-collected books, a Manytomany association can be established between user and book .@Entity Public classUser {PrivateList Books; @ManyToMany (targetentity= Package. Book.class)        PublicList getbooks () {returnBooks; }        Public voidsetbooks (List books) { This. books=Books; }} @Entity Public classBook {PrivateList users; @ManyToMany (targetentity= Package. Users.class, mappedby= "Books")        PublicList getusers () {returnusers; }        Public voidsetusers (List users) { This. users=users; }     }

The attributes of the two entities that are related to each other must be marked as @manytomany and specify the Targetentity attribute to each other.
Note that @manytomany annotations with only one entity need to specify the Mappedby attribute, which points to the Targetentity collection property name
Automatically generated tables with ORM tools in addition to the user and book tables, a User_book table is automatically generated for many-to-many associations

13

@MappedSuperclass

options available
@MappedSuperclass can pass a superclass's JPA annotations to subclasses, enabling subclasses to inherit the JPA annotations of the superclass
Example:

     @MappedSuperclass     publicclass  Employee () {       ...     }      @Entity     Publicclassextends  Employee {       ...     }     @Entity     Publicclassextends  Employee {       ...     }

14

@Embedded

options available
@Embedded combine several fields into a single class and act as a property of the entire entity.
For example, user includes the Id,name,city,street,zip property.
We want the City,street,zip property to be mapped to the Address object. This way, the user object will have the three properties of Id,name and address.
Address object must be defined as @embededable
Example:

     @Embeddable     publicclass  Address {city,street,zip}     @Entity       Public class User {       @Embedded       public  Address getaddress () {           ...       }     }

Hibernate validation Annotations

Annotations Type of application Description Example
@Pattern String Validating strings with regular expressions @Pattern (regex= "[A-z]{6}")
@Length String Verify the length of the string @length (MIN=3,MAX=20)
@Email String Verify that an email address is valid @email
@Range Long Verify that an integral type is within a valid range @Range (min=0,max=100)
@Min Long Verify that an integral type must be no less than the specified value @Min (value=10)
@Max Long Verify that an integral type must be no greater than the specified value @Max (VALUE=20)
@Size Collection or array Whether the size of the collection or array is within the specified range @Size (min=1,max=255)

Above source URL Hibernate entity class annotations

Attached: Cascade attribute value

1. None: Ignores other associated objects, default values.

2. save-upDate: When the session saves or updates an object through Save (), update (), Saveorupdate (), Cascade saves all the associated new temporary objects, and cascade updates all associated free objects.

3, persist: When the session through the persist () method to save the current object, Cascade saves all the associated new temporary objects.

4. Merge: When the current object is saved through the merge () method of the session, all associated free objects are cascaded.

5. Delete: When you delete the current object through Delete (), all associated objects are cascaded.

6. Lock: When the current free object is added to the session cache by lock (), all the free objects are added to the session cache.

7. ReplicatE: When the current object is copied through replicate (), all associated objects are cascaded.

8, evict: When the session cache object is cleared through evict (), all associated objects are cascaded.

9. Refresh: When the current object is refreshed with refresh (), all associated objects are cascaded. (refresh refers to updating data in session cache synchronously)

10, All:save-update (), persist (), merge (), delete (), lock (), replicate (), evict () and refresh () behavior.

11, Delete-orphan, removes all and the current object when the object that disassociate the behavior.

12, All-delete-orphan; When you delete the current object through Delete (), all associated objects are cascade-deleted.

Spring+hibernate entity class annotations Detailed (non-original) + Cascade attribute value

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.