In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
What is the EntityManager in java JPA? aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.
JPA, or Java Persistence API, is the specification provided for persistent data in Java EE. In using JPA, we often mention that Entity,Entity is an object that survives briefly in memory and is persisted in the database. Entity and the table mapping in the database, which is often referred to as ORM. We can persist an Entity, delete an Entity, or query the Entity through Java Persistence Query Language (JPQL).
Declare an entity by annotations as follows:
Java code
@ Entity
Public class Book {
@ Id
@ GeneratedValue
Private Long id
Private String title
Private Float price
Private String description
Private String isbn
Private Integer nbOfPage
Private Boolean illustrations
/ / Getters, setters
}
The mapping relationship between Book Entity and database is shown in the figure:
In JPA, all Entity are managed and manipulated through javax.persistence.EntityManager 's API. When EntityManager manages Entity, all Entity will have a unique identity (which is usually the primary key column), and the status of the Entity will be synchronized with the database. When Entity is detached from the management of EntityManager, Entity becomes a normal instance of Java object, and its state is detached.
When we create a new Entity with the new keyword, the Entity object exists in memory and JPA knows nothing about it. Only when EntityManager starts to manage it will its state be synchronized with the database. When the EntityManager.remove method is called, it is deleted from the database, but the Java object remains in memory until it is garbage collected.
Before we introduce EntityManager API, let's look at the concept of Persistence Context. A Persistence Context is a collection of managed Entity for a period of time in a thing. Multiple Entity instances with the same unique identity cannot exist in the same Persistence Context. For example, if the ID of a Book instance is 12, no Book instance with a second ID of 12 can exist in the same Persistence Context. Only Enitity that exists in Persistence Context will be managed by EntityManager and their state will be reflected in the database. Persistence Context can be seen as a first-level cache, and it can be used by EntityManager as a cache space for Entity. By default, Entity lives in Persistence Context until the end of the user's business.
Each transaction user has its own Persistence Context. An example of multiple Persistence Context accessing the same database is shown below:
We can call the EntityManager.persist () method to persist an Entity, that is, to insert data into the database.
Java code
Customer customer = new Customer ("Antony", "Balla", "tballa@mail.com")
Address address = new Address ("Ritherdon Rd", "London", "8QE", "UK")
Customer.setAddress (address)
Tx.begin ()
Em.persist (customer)
Em.persist (address)
Tx.commit ()
Customer and Address in the above example are two ordinary Java objects. When the persist method is called by EntityManager, both objects become Entity managed by EntityManager. When Transaction is submitted, their data is inserted into the database. The Customer object here is the holder of the object relationship, and its corresponding table structure should have a foreign key to correspond to the Address object.
Let's notice the order in which the two objects are stored. Even if the order of the storage of two objects is reversed, it will not cause an error that the foreign key cannot be found. As we have said before, Persistence Context can be seen as a first-tier cache. Before the transaction is committed, all the data is in memory, and there is no access to the database. EntityManager caches the data, and when the data is ready, it updates the data to the database in the order expected by the underlying database.
To find an Entity, there are two similar methods, the code is as follows:
Java code
Customer customer = em.find (Customer.class, 1234L)
If (customerships = null) {
/ / processing objects
}
Try {
Customer customer = em.getReference (Customer.class, 1234L)
/ / processing objects
} catch (EntityNotFoundException ex) {
/ / Entity was not found
}
The find method returns an Entity based on the primary key, or null if the primary key does not exist in the database. The getReference and find methods are similar, but only a reference to Entity is returned, not the data in it. It is used in situations where we need an Entity object and its primary key but no specific data. As shown in the example, when Entity cannot be found, EntityNotFoundException throws.
An Entity can be deleted through EntityManager.remove (), and once the Entity is deleted, it is also deleted in the database and is detached from EntityManager management (detached). This object can no longer be synchronized with the data in the database.
Java code
Tx.begin ()
Em.remove (customer)
Tx.commit ()
In all previous examples, the synchronization of data with the database occurred when the transaction was submitted. All the changes to be executed require the execution of a SQL statement. For example, in the following code, two insert statements are executed in the database where the transaction is submitted.
Java code
Tx.begin ()
Em.persist (customer)
Em.persist (address)
Tx.commit ()
In most cases, this synchronization mechanism with the database can meet the needs of our program. If we want to immediately reflect the changes to the data in Persistence Context to the database, we can do so by calling the flush method. Or if we want to synchronize the data in the database back to Persistence Context, we can call the refresh method. When the application calls the flush method and then calls the rollback method, all data synchronized to the database is rolled back.
This synchronization mechanism is much like we execute multiple SQL statements directly in sqlplus. When the flush method is explicitly called, it is equivalent to executing the SQL statement that we have entered, but without committing the transaction. When the tx.commit method is called, the thing is actually committed. If the flush method is not called, the SQL statement that has been entered is executed before committing the transaction when the tx.commit method is called.
Java code
Tx.begin ()
Em.persist (customer)
Em.flush ()
Em.persist (address)
Tx.commit ()
In the above code example, the order in which persist is executed is guaranteed. Because when the flush method is called, the change has been synchronized to the database, that is, the SQL statement has been executed, if the order of the two persist methods is reversed, there will be an exception of foreign key constraints.
The effect of the refresh method can be shown by the following example:
Java code
Customer customer = em.find (Customer.class, 1234L)
AssertEquals (customer.getFirstName (), "Antony")
Customer.setFirstName ("William")
Em.refresh (customer)
AssertEquals (customer.getFirstName (), "Antony"); ")
The contains method returns a Boolean value to detect whether an Entity exists in the current Persistence Context.
Java code
Customer customer = new Customer ("Antony", "Balla", "tballa@mail.com")
Tx.begin ()
Em.persist (customer)
Tx.commit ()
AssertTrue (em.contains (customer))
Tx.begin ()
Em.remove (customer)
Tx.commit ()
AssertFalse (em.contains (customer))
The clear method clears the current Persistence Context, so that all Entity becomes detached state. The detach method simply changes an Entity into a detached state. As mentioned earlier, the Entity of detached will no longer be synchronized with the data in the database.
Java code
Customer customer = new Customer ("Antony", "Balla", "tballa@mail.com")
Tx.begin ()
Em.persist (customer)
Tx.commit ()
AssertTrue (em.contains (customer))
Em.detach (customer)
AssertFalse (em.contains (customer))
If we want to resynchronize an detached Entity with the data in the database, we can call the merge method. Imagine a scenario where we need to fetch an object from the database that becomes detached before being passed from the persistence layer to the presentation layer. In the presentation layer, some data in the Entity has changed, and we pass the Entity back to the persistence layer and make it a managed state to reflect the change to the database.
Java code
Customer customer = new Customer ("Antony", "Balla", "tballa@mail.com")
Tx.begin ()
Em.persist (customer)
Tx.commit ()
Em.clear ()
/ / set a new value to an entity of detached
Customer.setFirstName ("William")
Tx.begin ()
Em.merge (customer)
Tx.commit ()
Finally, we use a diagram to show how EntityManager changes the life cycle of an Entity.
The answer to the question about EntityManager in java JPA is shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.