Main content of JPA specifications

Source: Internet
Author: User
Entity Identity Entity ID
Generally, a single value is used as the entity identity.
When using the compsite primary key, you must create a primary key class that represents the primary key. In this way, the compsite primary key can be represented by an attribute (primary key class type) on the object.
The persistence framework uses entity identity for processing in many places. Therefore, the primary key class must correctly implement the equals and hashCode methods.
In addition, the application layer should note that do not modify the primary key value for the managed objects in the persistence context; otherwise, the persistence framework cannot guarantee the impact, because the persistence context can only identify the entity identity based on the entity identity.

Accessors of Persistent Fields and Properties
Persistent state (that is, fields or properties that require persistence) can be accessed in two types: field-based and property-based.
In field-based mode, the persistence framework directly accesses instance variables. in property-based mode, the getter and setter methods are used for access.
When using property-based, the setter and getter methods may contain business logic. For the application layer, note that when the persistence framework loads data from the database and assigns values to object attributes, the assignment order of each attribute cannot be guaranteed. Therefore, you need to pay attention to this in the business logic of getter and setter.
In addition, if property-based is declared as lazy-fetching, the application layer should not access the corresponding instance variable, because the persistence framework may inject setter and getter to implement lazy-fetching, directly accessing instance variable may not get the value
For Collection types, JPA requires that the Collection, Set, Map, and List Interfaces under java. util must be used. For the semantics of List, Set, Map, and Bag, refer to this post

Persistence Context

Persistence Context is an intermediate container to be maintained by the Persistence framework. It stores copies of managed objects, such as object objects obtained from the database or objects saved by the Persistence framework.
The main functions include: caching (such as the concept of a level-1 cache for NHibernate), supporting Flush operations, assisting in Entity and attribute Dirty checks, etc.
JPA divides the persistence context into two types: PersistenceContextType. TRANSACTION and PersistenceContextType. EXTENDED. The life cycle of the persistence context of the TRANSACTION type (default type) is the same as that of the transaction scope. For example, when the TRANSACTION starts, it is the start stage of the life cycle, and the end of the life cycle when the transaction is committed or rolled back. The life cycle of EXTENDED type is basically the same as that of EntityManager. It starts when EntityManager is created and ends when EntityManager is disabled. When implementing the Extended type persistence context, you must note that its lifecycle may span multiple transactions and is not within the transaction scope, it is accompanied by the impact on the lifecycle of the Instance Object and related operations in the persistence context, such as version control.

Entity Instance's Life Cycle Instance Object Lifecycle
For the life cycle of the Instance Object, refer to this post
The life cycle of an instance object has four states:
New: the newly created instance object with no identity value
Managed Objects in persistent Context
Detached: Instance Object outside the persistent Context
Removed: the object of the deleted instance.
JPA defines in detail the Transition Relationship Between the lifecycle states when the instance object is accompanied by various operations of EntityManager.

JPA declares several callback methods of entity instance life cycle: PrePersist, PostPersist, PreRemove, PostRemove, PreUpdate, PostUpdate, and PostLoad. Its semantics is described in detail.

Entity Relationships Entity relationship
JPA defines four relationships: one-to-one, one-to-one, two-to-one, and one-to-one.

Owning side: All Parties and Inverse parties of the Inverse side relationship
The owner of a link is owning side, and the other is inverse side. The owner of the link can understand that after the instance of the owner is deleted, any information about the two-party relationship disappears completely. Assume that the logical Table A has A foreign key that is referenced from the primary key of Table B (logically, this foreign key relationship is not established in the database ), if you delete b1 from A piece of data in Table B, the association between the corresponding instance objects between A and B may not be completely eliminated, because Table A may still have A data a1 That references the primary key value of b1, the object class corresponding to B is not owning side.
Therefore, the party that owns the foreign key is the owning side, which is clear in the one-to-one relationship; in one-to-one and one-to-one, the owning side of the queue; either side of the queue-to-queue can act as the owning side.
Owning side and inverse side will serve as one of the basis for cascade-related operations.

JPA defines in detail the following ing processing methods by default:
Bidirectional one-to-one; bidirectional one-to-least, parallel-to-one; unidirectional single-valued (unidirectional one-to-one, parallel-to-one ); bidirectional upload-to-sequence; unidirectional multi-valued (unidirectional one-to-sequence, unidirectional-to-sequence)

Inheritance
Inheritance Mapping Strategies includes:
Single table per class hierarchy, which uses a discriminator column to distinguish sub-classes. The advantage is that it supports polymorphism and query. The disadvantage is that the field unique to the sub-class must be null.
Table per concrete entity class. The disadvantage is that it does not support polymorphism. Generally, you must use separate SQL statements for each subclass or use UNION statements.
The difference between Joined subclass and table per concrete entity class is that the superclass of Public attributes is stored in a table. This policy also supports polymorphism, but the disadvantage is that multiple JOIN relationships are required.
For details, refer to this post

Optimistic Locking and Concurrency Optimistic locks and Concurrency Control
By default, the application layer of JPA uses the optimistic lock mechanism.
When Optimistic Locking is used, entity must declare a version attribute. The value of this field is automatically maintained by the persistence framework and cannot be modified at the application layer. The persistence framework can introduce other mechanisms to implement optimistic lock check, or implement more fine-grained optimistic lock control. JPA does not require any
The Optimistic Locking Mechanism of JPA is based on data rows.

In JPA, the Lock Mode is declared to achieve the pessimistic Lock effect. As for the implementation method, you only need to ensure that P1: dirty read, P2: non-repeatable read does not exist.
LockModeType supports READ and WRITE.
For the WRITE mode, when the isolation level is read commited, the database can ensure that there are no P1 or P2 conditions.
In READ mode, database locks are generally used to implement pessimistic locks.

Query Language
SQL-like syntax, but with obvious Object Features
Three statements, SELECT, UPDATE, and DELETE, are declared.

Let's look at the general features with a simple example.
1. Use associations between entities Select distinct o
FROM Order o JOIN o. lineItems l JOIN l. product p
WHERE p. productType = 'Office _ supplies'

The JOIN clause no longer requires the ON condition section because the association between objects has been defined.

2. Collection Member Declarations Select distinct o
FROM Order o, IN (o. lineItems) l
WHERE l. product. productType = 'Office _ supplies'

It is equivalent to the statement in 1.
The FROM clause defines the alias o (Identification Variables); o. lineItems is a collection type attribute, IN (o. lineItems) l semantics: The lineItems of the Order instance object must meet the subsequent conditions, and l represents each object in lineItems. The WHERE clause further declares the filtering conditions for l.

In JPA, the expression l. product is called path expression (An identification variable followed by the navigation operator (.) and a state-field or association-field is a path expression)
There are three types of content after each dot in path express: persistent field, single-valued relationship field, and collection-valued relationship field. For collection-valued relationship fieldSpecific scenariosUse
For example, in the example 1 and 2 above, if lineItems is not a set type, the statements in the two examples are equivalent to the following statement (the lineItems attribute is changed to lineItem to distinguish it from the set concept ):
3. Select distinct o
FROM Order o
WHERE o. lineItem. product. productType = 'Office _ supplies'

For the associations in path expressions, JPA requires the inner join operation. Therefore, the preceding statements are equivalent to the preceding examples 1 and 2.
However, when lineItems is set to collection-valued relationship field, the preceding statement is not supported and must be 1 or 2.
Specific scenariosIncluding the JOIN clause and Collection Member Declarations as shown in the preceding example, and can be used in Empty Collection Comparison Expressions and Collection Member Expressions.

4. Empty collection comparison expressions SELECT o
FROM Order o
WHERE o. lineItems IS [NOT] EMPTY

5. Collection Member Expressions SELECT o
FROM Order o
WHERE: lineItem MEMBER [OF] o. lineItems

: LineItem is a variable. In the application, a lineItem instance object is assigned to the variable. The preceding query syntax is: locate: The Order instance object associated with the lineItem object.

6. ALL and ANY Expressions SELECT emp
FROM Employee emp
WHERE emp. salary> ALL (
SELECT m. salary
FROM Manager m
WHERE m. department = emp. department)

ALL and ANY expressions are used for subqueries.
Above emp. salary> ALL (...), emp. salary must be greater than all values returned by the subquery. If the subquery does not have a qualified record, emp. salary> ALL (...) this condition is true.
Change the keyword ALL in the preceding example to the ANY (or SOME) keyword, which indicates emp. salary meets the condition as long as it is greater than the partial score returned by the subquery. If the subquery does not have a record that meets the condition, emp. salary> ANY (...) this condition is false. If all the results returned by the subquery are greater than or equal to emp. salary, the condition is false.

7. Constructor Expressions
Using constructor expressions, you can specify to use a specific constructor to return the Instance object List, instead of the object array list. Select new com. xyz. CustomerDetail (c. name, c. country. name)
FROM customer c
WHERE c. lastname = 'oss' AND c. firstname = 'roxane'

8. A few more examples
Find all orders that have line items: Select distinct o
FROM Order o, IN (o. lineItems) l

Or: SELECT o
FROM Order o
WHERE o. lineItems IS NOT EMPTY

Find all orders that have no line items: SELECT o
FROM Order o
WHERE o. lineItems IS EMPTY

Through the above examples, we can see that the JPA query language has a strong object expression capability.

The primary purpose of the UPDATE and DELETE statements is to provide bulk update and delete operations.
Some functions are also declared in JPA, most of which are basic functions in the SQL standard.

When implementing the JPA standard query language, one of the key aspects to be processed is the multi-state query. The entity class name in the statement may be abstract or supperclass, the query parser must be able to process such multi-state queries. For example, NHibernate (does not know whether the current version has been changed to anlr for parsing) is easier to analyze and query statements. Every time an entity class is encountered, it is searched for whether a subclass exists, if yes, a query statement is generated for each Subclass, and the results are merged using JOIN, UNION, or separate execution of each statement (nhibass does not support Union Subclass). Only partial polymorphism is achieved. To achieve full polymorphism, the situation and the things to be processed are complicated.
There are many other details. For example, persistence context may cache some update operations and write back to the database while waiting for Flush. However, to ensure the consistency of the query results, before executing a query, you must at least apply the update cache of the objects in the persistence context to the database.

Metadata
For detailed metadata declaration specifications, refer to the description section of JPA for annotation and XML descriptor.

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.