JPA Learning Notes (+)--JPA Advanced

Source: Internet
Author: User

1.JPA Solid life cycle:

JPA entities have the following 4 Life cycle states:

(1). New: Instantaneous object, no ID yet, and object associated with persistence context.

(2). Managed: Persisted managed object, with ID value, has already established an associated object with persistence context.

(3). Datached: A free-form offline object with an ID value, but no associated object with persistence context.

(4). Removed: Deleted objects, with ID values, are associated with persistence context, but are ready to be removed from the database.

Summary of four states:

Status name exists in the entity manager as a Java object exists in the database

New Yes No no

Managed Yes Yes Yes

Detached No No No

Removed Yes yes No

2.JPA switching of solid state:

You can switch between the four states of a JPA entity, as follows:

3. Entitymanager Entity manager for container management and application management:

There are two ways to manage the entity manager in JPA:

(1). Container Management (Container-manager) entity Manager:

The container Management entity manager, which is the entity manager managed by the Java EE container, generates the entity manager by Persistencecontext Injection, with the following code:

@PersistenceContext (unitname= "persistence Unit name")

Protected Entitymanagerem;

(2). Application Management (Application-manager) entity Manager:

JPA can be used not only in Java EE containers, but also out of Java EE containers in the Javase program, and when JPA is out of the Java EE Server environment, it needs to get the entity manager through the application, with the following code:

A. Code mode:

First create the Entity manager factory based on the persistence unit

ENTITYMANAGERFACTORYEMF = persistence.createentitymanagerfacotory (persistent unit name in persistent policy file);

Creating an Entity manager from the Entity manager factory

Entitymanager em= Emf.createentitymanager ();

B. Annotation method:

Injecting a persistence unit into the Entity manager factory

@PersistenceUnit (persistent unit name)

protected entitymanagerfactory EMF;

Protected Entitymanager em = Emf.createentitymanager ();

Note: When there is only one persistence unit in the persistence policy file, no supporting cell names are specified in the annotations.

Common methods of 4.JPA entity manager:

(1). Find lookup: Equivalent to a get operation in Hibernate, if the first-level cache lookup does not immediately go to the database lookup, if the lookup does not return NULL.

(2). GetReference Lookup: Equivalent to hibernate in the load operation, if the first-level cache does not find and not immediately go to the database lookup, but to find a level two cache, return the agent of the entity object, If the lookup is not thrown objectnotfindexception.

(3). Persist: Changes the entity class from the new state or removed to the managed state, and saves the data to the underlying database.

(4). Remove: Turns the entity into a removed state, and the data is actually deleted when the entity manager is closed or refreshed.

(5). Flush: Synchronize the entity with the underlying database, and when the persist, merge, or remove methods are called, the updates are not immediately synchronized to the database until the container decides to flush to the database and the Flush force flush can be called.

(6). CreateQuery: The query object is defined according to JPA QL.

(7). Createnativequery: Allows developers to query operations based on the SQL syntax of a particular database, which is only used when JPA QL does not meet the requirements, and is not recommended because of increased program portability.

(8). Createnamedquery: Creates a query object based on the named query labeled in the entity.

(9). Merge: Persist a detached entity to the database and convert to the managed state.

5.JPA Paging Query:

(1). Query object settings created for the entity manager returns the maximum number of results: setmaxresults (int maxresult);
(2). Query object settings created for the Entity manager return results start subscript: setfirstresult (int firstresult);
Call the stored procedure in 6.JPA:

Note: Only two stored procedures can be called in JPA: 1. A stored procedure with no return value. 2. Return a stored procedure with a value of resultset (cannot be out).

The Entity manager's Createnativequery ("{Call stored Procedure name ()}"), which invokes the database's stored procedure.

Named parameters for 7.JPA:

Syntax: ": Parameter name".

For example:

Query query = Entitymanager.createquery ("Selectu from User u where U.name=:name");

To set named parameters in a query

Query.setparameter ("name", testname);

Note: You are not allowed to use two named parameters of the same name in the same query.

Position parameters for 8.JPA:

Syntax: "? Positional parameter index.

For example:

Query query = Entitymanager.createquery ("Selectu from User u where u.name=?1");

Set positional parameters in a query

Query.setparameter (1, testname);

Note: The positional parameter index value in JPA starts at 1.

9.JPA Collection query:

We know that in SQL statements, finding whether an element is often used in a collection like: In (a,b,c) query statements, in JDBC we often need to stitch together the collection elements into a comma (",") delimited string, There are two methods in JPA that make it easy to determine whether an element is a query in a collection:

(1). Set parameters for the collection type:

The Setparameter method of a Query object supports object types, so you can pass in parameters of a collection type, such as an array or ArrayList.

For example:

Query query = em.createquery ("select * fromusers where name in (? names)");

Query.setparameter ("name", names);//names is a name collection

(2). Using the member of keywords:

For example:

Select t from Topic t where:option memberof t.options;

callback method for 10.JPA:

In JPA, the entity class supports a number of callback methods that can be specified by the following annotations:

(1) [Email protected]: Occurs immediately after the persist method call, and the Cascade Save also occurs when the data is not actually inserted into the database.

(2) [Email protected]: The data has been inserted into the database and then triggered.

(3) [Email protected]: triggered before an entity is deleted from the database. Cascading deletes also trigger the event, at which point the data is not actually deleted from the database.

(4) [Email protected]: triggered after the entity has been deleted from the database.

(5) [Email protected]: triggered before the state of the entity is synchronized to the database, the data is not actually updated to the database.

(6) [Email protected]: triggered after the state of the entity is synchronized to the database, the synchronization occurs when the transaction commits.

(7) [Email protected]: triggered in the following situations:

A. Executing the Find or GetReference method after loading an entity.

B. After implementing the JPA QL query.

After the C.refresh method is called.

11. Transaction Management Features:

A logical unit of work for the firm's database that contains a series of operations with four properties, the acid characteristic:

(1). Atomic (atomicity):

Each operation in a transaction is inseparable, and the operations contained in the transaction are treated as a logical unit, and the operations in the logical unit either succeed or fail altogether.

(2). Consistency (consistency):

Consistency means that only legitimate data can be written to the database, and if there is any non-conformance to the data, the transaction should roll it back.

(3). Isolation (Isolation):

Transactions allow multiple users to concurrently access the same data without destroying the correctness and integrity of the data. At the same time, the modification of parallel transactions must be independent of the modifications of other parallel transactions. According to the strict isolation logic, the data that one transaction sees is either the state before another transaction modifies the data, or the data that the transaction has been modified to complete, and it must not be the data that is being modified by other transactions.

(4). Durability (persistent):

After the transaction ends, the results of the transaction must be persisted.

12.3 uncertainties that may occur during data manipulation:

(1). Dirty reads:

One transaction has read uncommitted data from another parallel transaction.

(2). Non-repeatable reading:

When a transaction reads the data that was previously read, it finds that the data has been modified by another committed transaction.

(3). Phantom read:

The same query occurs more than once in the same transaction, and because other transactions commit the action, each time a different result set is returned, resulting in a change of read.

13. Isolation level of the transaction:

Transaction isolation means that a database (or other transactional system) is split between multiple transactions in parallel by some mechanism, so that each transaction remains independent during its execution, as if only one transaction is currently running alone. To avoid the occurrence of uncertainties in 12, 3, the standard SQL specification defines the following 4 transaction isolation levels:

(1). Read for submission:

The lowest level of transaction isolation ensures that no illegal data is read during the read process.

(2). Read submitted:

Transaction isolation at this level guarantees that a transaction does not read to another parallel transaction that has been modified but uncommitted and avoids dirty reads. The default transaction isolation level for most mainstream databases is read-committed.

(3). Repeat read:

Transaction isolation at this level avoids dirty reads and non-repeatable reads, but it also means that one transaction may update data that has been read by another transaction but not committed.

(4). Serialization:

The highest level of transaction isolation also provides the strictest isolation mechanism, which can be avoided for the above 3 types of uncertainties. This level simulates the serial execution of a transaction, logically as if all the transactions were in one execution queue, serially executed sequentially rather than parallel execution.

Summary of 4 transaction isolation levels:

Isolation level dirty read non-repeatable read Phantom read

Uncommitted reads may be possible

The submission of reading may not be possible

Repeated reading cannot possibly be

Serialization cannot possibly be impossible

9. JDBC Transaction and JTA transaction:

JDBC Transaction: Can only support one database, single data source, one by the database itself to perform commit or rollback, single phase commit, local transaction. The JDBC transaction is managed by connection and the transaction cycle is limited to the connection life cycle.

JTA Transaction: JTA provides transaction management capabilities across sessions, supports distributed transactions for multiple data sources, and two-phase commits. JTA transaction management is implemented by the JTA container, the JTA container dispatches the many connection that are currently joining the transaction, implements its transactional requirements, and the JTA transaction cycle can span multiple JDBC connection life cycles.

10. Propagation characteristics of a transaction:

The transactional propagation attribute is used to specify how transactions are used when doing operations, with the following 6 transactional propagation characteristics in JPA:

(1). Not supporting: not supported, pending if the current transaction has context.

(2). Support: Supports, if there is a transaction, the transaction is used, and if there is no transaction, the transaction is not used.

(3). Required: Required, if there is a transaction, use is used, and if there is no transaction, a new transaction is created.

(4). Required: New transactions are required, each time a new transaction is created.

(5). Mandatory: There must be a transaction, and if there is no transaction, an exception is thrown.

(6). Never: There must be no transaction, and if there is a transaction, an exception is thrown.

16. Mechanism of the Lock:

The so-called lock, which is to add a limit to the selected target object, so that it can not be modified by other programs, JPA supports two kinds of locking mechanism: optimistic and pessimistic lock.

(1). Pessimistic Lock:

Conservative attitude to the data by external modification, in the whole process of data processing, will be locked, pessimistic lock implementation, often rely on the lock mechanism provided by the database. The most common pessimistic lock is to add "for update" to the query with the following usage:

SELECT * from user where name= "test" forupdate

In JPA, you can set the mode of pessimistic locking by setting the lock mode (query.setlockmode) for the query object:

A.lockmode.none: no lock mechanism.

B.lockmode.write: Locks are automatically added at insert and update.

C.lockmode.read: Locks are automatically added when the record is read.

D.lockmode.upgrade: Use the database's for UPDATE clause to lock.

(2). Optimistic Lock:

Relative to pessimistic lock, optimistic locking mechanism adopts more relaxed locking mechanism, pessimistic lock relies on the mechanism of database lock in most cases to ensure the maximum degree of exclusivity, but the performance cost of the database is relatively large. Optimistic locks are mostly implemented based on the data version record or timestamp mechanism.

The version-based optimistic lock reads the version number of the data when it reads the data, and then updates the version number by 1, and the version of the data is compared to the corresponding version in the database when it is submitted, and is updated if the data version number of the submission is hit in the current version number in the database, otherwise it is considered to be outdated data. Optimistic locking greatly reduces the database overhead and improves the performance of the program.

In JPA, you can use @version annotations in entities to specify that they use optimistic locks, and JPA automatically generates and maintains a list of version numbers in the table corresponding to the database.

17.Spring Integrated JPA:

Not only can JPA be used in a Java EE environment, but it can also be used in a javase environment, and spring is now very widely used in development, and spring also provides strong support for JPA. The steps for spring integrated JPA are as follows:
(1). Under Mate-inf, add the JPA persistence policy file to develop the entity bean.

(2). Spring support is introduced for the project. Add spring dependent and spring configuration files.

(3). Include the JPA configuration in the spring configuration file as follows:

<bean id= "Entitymanagerfactory"

class= "Org.springframework.orm.jpa.LocalEntityManagerFactoryBean" >

<propertyname= "Persistenceunitname" value= "Persistence unit name"/>

</bean>

<bean id= "TransactionManager"

class= "Org.springframework.orm.jpa.JpaTransactionManager" >

<propertyname= "Entitymanagerfactory" ref= "Entitymanagerfactory"/>

</bean>

<tx:annotation-driventransaction-manager= "TransactionManager"/>

At this point, the simple integration of spring and JPA is complete.

JPA Learning Notes (+)--JPA Advanced

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.