JPA & ORM

Source: Internet
Author: User

JPA (Java Persistence API) is the Java Persistence specification proposed by Sun. It provides Java developers with an object/relational mapping tool to manage relational data in Java applications

There are two different ways to annotate a class into an entity class in JPA: attribute-based (property-based) and field-based (field-based) annotations
Field-based annotations, where annotations are placed directly in front of the fields of the entity class
Attribute-based annotations are the direct placement of annotations in front of the corresponding getter methods of the entity class (this is the opposite of spring), but only one of the annotations must be used in the same entity class
Entity, Table, Id, Generatedvalue, Basic, Column, temporal, Transient, Lob, Transient, secondarytable, embeddable, Embedded

JPA annotations
(1) Entity
@javax. persistence.entity (name= "xxx")
Name specifies the names of the entity beans, the default value is the unqualified class name of the Bean class, and the select O from xxx o where o.id=?1

(2) Table
@javax. Persistence.table (catalog= "xx", name= "xx", schema= "xx", uniqueconstraints={@UniqueConstraint (columnnames={ "XX", "XX"})})
Name: Specify the names of the tables
Catalog: Specifying the database name
Schema: Specify the user name of the database
Uniqueconstraints: Specify uniqueness field constraints, such as specifying uniqueness constraints for PersonID and name fields
uniqueconstraints={@UniqueConstraint (columnnames={"PersonID", "Name"})}

(3) Id
@javax. Persistence.id ()
A property that maps to the primary key of a database table, and an entity can have only one property mapped to the primary key.

(4) Generatedvalue
@javax. Persistence.generatedvalue (generator= "xxx", Strategy=generationtype.auto)
Strategy: Represents the primary key generation strategy with Auto,indentity,sequence and TABLE 4
Each means that the ORM framework is automatically selected, generated according to 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, and the default is 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.
Hibernate UUID
@Id @GeneratedValue (generator= "System-uuid")
@GenericGenerator (name= "System-uuid", strategy = "uuid")

(5) Basic
@javax. Persistence.basic (Fetch=fetchtype.lazy,optional=true)
Fetch: Crawl strategy, delay loading and immediate loading
Optional: Specifies whether the field is allowed to be NULL when building the database structure

(6) Column
@javax. Persistence.column (length=15,nullable=false,columndefinition= "", insertable=true,scale=10,table= "", Updatable=true)
@Column annotations Specify a detailed definition of a field
Name: The names of the fields, which are identical to the property names by default
Nullable: If NULL is allowed, the default is True
Unique: is unique, false by default
Length: field lengths, only valid for fields of type string
ColumnDefinition: Represents the actual type of the field in the database
Usually the ORM framework can automatically determine the type of field in a database based on the type of attribute.
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, which is useful if you want to map a string type to a blob or text field type of a specific database
such as: @Column (name= "BIRTH", nullable= "false", columndefinition= "DATE")
Insertable: By default, the JPA persistence provider assumes that all columns are always included in the SQL INSERT statement.
If the column should not be included in these statements, set Insertable to False
Updatable: Columns are always included in the SQL UPDATE statement. If the column should not be included in these statements, set updatable to False
Table: All persisted fields of an entity are stored in a database table whose name is the entity name, if the column is associated with a @SecondaryTable table
String name to set name to the corresponding secondary table name

(7) Temporal
@javax. Persistence.temporal (Temporaltype.date)
Value:temporaltype.date,temporaltype.time,temporaltype.timestamp Time Type format

(8) Enumerated
@javax. persistence.enumerated (enumtype.string)
Value:enumtype.string,enumtype.ordinal
Enumeration type member property mapping, enumtype.string specifies that the property is mapped to a string, enumtype.ordinal specifies that the attribute is mapped to the data order


(9) Lob
@javax. Persistence.lob
Used for labeling field types CLOB and BLOB types
Clob (Character Large ojects) type is a long string type, the entity can be of type char[], character[], or String type
Blob (Binary Large Objects) types are byte types, entities can be of type byte[], byte[], or classes that implement serializable interfaces.
Typically using lazy loading, @Basic (Fetch=fetchtype.lazy)

(10) Transient
@javax. persistence.transient
@Transient indicates that the property is not a mapping to a field in a database table, the ORM framework ignores the property

(11) Secondarytable
@javax. persistence.secondarytable
Map an entity to multiple database tables
Such as:
@Entity
@SecondaryTables ({
@SecondaryTable (name = "Address"),
@SecondaryTable (name = "Comments")
})
public class Forum implements Serializable {
@Column (table = "Address", length = 100)
Private String Street;
@Column (table = "Address", Nullable = False)
Private String City;
@Column (table = "Address")
Private String conutry;
@Column (table = "Comments")
Private String title;
@Column (table = "Comments")
Private String Comments;
@Column (table = "Comments")
}
The value of the table property specifies the table name that the field stores
The default fields for changing properties without @Column annotations will be present in the Forum table

(@Embeddable)
@javax. persistence.embeddable
Nested mappings, using embeddable annotations in nested classes, indicate that this is a class that can be nested, using @Embedded
When the same class is nested in a class with different annotation methods, some errors may occur, using the @Access (AccessType. FIELD) Sets the annotation method for nested classes

================================================================================================
(1)
@Entity Annotation Definitions
@Target (TYPE) @Retention (RUNTIME)
Public @interface entity{
String name () default ""; The name of the entity bean
}


(2)
@Table Annotation Definitions
@Target (value = {Elementtype.type})
@Retention (value = retentionpolicy.runtime)
Public @interface Table {
Public String name () default ""; Name of the table
Public String catalog () default ""; Database name
Public String schema () default ""; Database user Name
Public uniqueconstraint[] Uniqueconstraints () default {}; Specify multiple field uniqueness constraints
}


(3)
@UniqueConstraint Annotation Definitions
Public @interface uniqueconstraint{
String[] ColumnNames (); Unique Field Property name
}


(4)
@Id Annotation Definitions
@Target ({METHOD, FIELD}) @Retention (RUNTIME)
Public @interface id{}


(5)
@ annotation Generatedvalue Definition
@Target ({METHOD, FIELD}) @Retention (RUNTIME)
Public @interface generatedvalue{
GenerationType strategy () default AUTO; Primary key generation Policy
String generator () default "";
}


(6)
@Column Annotation Definitions
@Target (value = {elementtype.method, elementtype.field})
@Retention (value = retentionpolicy.runtime)
Public @interface Column {
Public String name () default ""; column names in the database
public boolean unique () default false; Whether the column is unique
public boolean nullable () default true; Whether it is possible to empty
public boolean insertable () default true;
public boolean updatable () default true;
Public String columndefinition () default "";
Public String table () default "";
public int Length () default 255; The maximum length of the column
public int precision () default 0;
public int scale () default 0;
}


(7)
@Temporal Annotation Definitions
public enum temporaltype{
Date,//represents date type Java.sql.Date 2008-08-08
Time,//on behalf of the type Java.sql.Time 20:00:00
TIMESTAMP//Representative time Java.sql.Timestamp 2008-08-08 20:00:00.000000001
}
public enum temporaltype{
Date,//represents date type//java.sql.date 2008-08-08
Time,//on behalf of the type//java.sql.time 20:00:00
TIMESTAMP//Representative time//java.sql.timestamp 2008-08-08 20:00:00.000000001
}

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

Targetentity: Represents the entity type that the attribute is associated with. This property is not normally 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, like @Column, a mediator describes not a simple field, but one by one associated fields, for example. A field that describes a @manytoone.

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

Ten , @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;

}

One , @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;

}

A , @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, such as:p ackage. Book.class

Mappedby: The corresponding collection property name of another entity class that represents a many-to-many association

JPA & ORM

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.