Persistent API (JPA) series (iv) Manager entitymanager--performing database updates

Source: Internet
Author: User
Tags java se


Entitymanager is an interface that applies to entities in the persistence context to manipulate entity beans. We can use it to create, delete, modify persisted entities to reflect the database, or to query the database for a list of entities or entities. All of these operations are done through the entity manager.
This article will first explain how the Entitymanager object is referenced, and then explain the various operations of the database using the Entitymanager operation function, including the following.

Persistent entity persist (): Inserts data into the data table.

Delete entity remove (): Deletes a record from the data table.

Update entity merge (): Update data table records.

Refreshes the entity to Database Flush ().

Set Flush Refresh Mode Setflushmode ().

Refresh entity Refresh (): Updates from the data table.

Query entity by primary key find (): Queries records from the data table.

Detects if the entity is managed contains ().

Detached managed entity clear ().

=============================================================================
1. How to refer to Entitymanager objects
Depending on the scenario that the entity manager applies to, you can divide it into two types.
1) Container-managed Entitymanager
Container-managed Entitymanager objects must run in the EJB container, not in the Web container and in the Java SE environment. The Entitymanager object in the example in the previous section is obtained from the container by injecting the @persistencecontext annotation, which is the container-managed way to get the Entitymanager object. This is easiest to use, and developers do not have to consider complex issues such as the creation of Entitymanager objects, transactions, etc., all of which are given to the container to manage. The object is obtained in the following way:
@PersistenceContext (unitname= "demo")
Entitymanager em;
2) Apply the managed Entitymanager
Application-managed Entitymanager objects can be run in the EJB container or out of the EJB container, and integrate with any Java environment, such as the Web container, the Java SE environment, and so on. It requires the developer to manually control its creation, release, transactions, and so on, which are more complex operations. The object is obtained in the following way:
Entitymanagerfactory emf = Persistence.createentitymanagerfactory ("demo");
Entitymanager em = Emf.getentitymanager ();


Because our company's project runs in the EJB container of JBoss, it is used in the first way.


= = Feature: Updates are not synchronized to the database immediately =====================================================

1. Persistent entity persist ()--inserting data into a data table
The main task of the DAO layer is to persist the Entitymanager managed entities to the database, to write the in-memory entity objects to the data table, and to reflect a new row of records in the table.
The Persistence method is:
Em.persist (obj);
Similar to the following SQL statement executed:
INSERT into student (name, sex, age, birthday, telephone, address) VALUES (' Liuzhong soldier ', 1, 25, ' 1981-05-04 ', ' 12345678 ', ' Beijing ');

2. Delete entity remove ()--delete a record from the data table
When you need to delete an entity object that has been persisted to the database
Object obj = Em.find (clazz, id);
Em.remove (obj);
For example:
Student Student = Em.find (Student.class, 1);
Em.remove (student);
Similar to the following SQL statement executed:
Delete from student where id=1;

3. Update entity Merge ()--Update data table record
Update an Entity object that has been persisted
Object updatedobj = Em.merge (obj);
For example:
Student Student = Em.find (Student.class, 1);
Student.setname ("liuzhongbing");
Em.merge (student);
Similar to the following SQL statement executed:
Update student set name= "liuzhongbing" where id=1;

When executing the Em.merge (student) method, there are two execution rules:
If there is already a container-managed student instance with the same ID in the container, the container will copy the contents of the parameter student into the managed instance, and the merge () method returns the managed instance, but the parameter student is still detached and not managed. The container synchronizes the instance to the database when it decides to flush.
A student instance with the same ID does not exist in the container. The container copies a container-managed student instance according to the student parameter passed in, and the merge () method returns the managed instance, but the parameter student is still detached and not managed. The container synchronizes the instance to the database when it decides to flush.


= = Feature: Refresh entity sync to database =========================================================
1. Refresh entity to Database flush ()
When persist (), merge (), and remove () methods are called, updates are not immediately synchronized to the database until the container decides to flush into the database. By default, the container determines whether the refresh occurs before the "related query" executes or when the transaction commits, and of course the "related query", except for Find () and getreference (), does not cause the container to trigger a flush action if you need to flush the update to the database before the transaction commits. You can call the Entitymanager.flush () method directly. In this case, you can manually refresh the database to gain maximum control over the database operation.


When the entity is being managed by the container, you can call the entity's Setxxx () method to modify the data, and when the container determines flush, the updated data is synchronized to the database. If you want the modified data to be synced to the database instantly, you can execute the Flush () method:
Em. Flush (obj);
The function will do two things:
Commit the changed fields to the database.
Refreshes the fields in the database into the entity.
For example:
Student Student = Em.find (Student.class, 1);
Student.setname ("liuzhongbing");
Em.flush (student);

The difference between this and the above implementation of merge () is as follows.
The object being submitted is different: flush () commits the container-managed object to the database, and merge () can submit not only the container-managed object, but also the object that is not managed by the container.
The timing of the submission is different: flush () synchronizes to the database immediately, and merge () synchronizes only when the container needs to flush.

2. Set Flush Refresh Mode Setflushmode ()
The flush () function above is called manually, and can only be dependent on the container's automatic refresh if it is not manually invoked. The container is automatically refreshed by default because it corresponds to the refreshed auto value:
public enum Flushmodetype {
AUTO,
COMMIT
}
We can call the following method to change the refresh mode:
Em.setflushmode (Flushmodetype.commit);
The differences between the two modes are as follows.
AUTO: Refreshes occur before the query statement executes (except for the Find () and getreference () queries) or transaction commits, and is suitable for execution when there are no query statements (except for Find () and getreference () queries) during the bulk update of the data.
COMMIT: Refreshes occur only when a transaction commits, and is appropriate for the presence of query statements (except for the Find () and getreference () queries) during the bulk update of the data.
The difference between the two modes is reflected in the execution of the database's underlying SQL, that is, the number of times the JDBC driver interacts with the database. The commit mode enables updates to be done only once in a network interaction, while auto mode may require multiple interactions, which triggers how many times the network interaction is generated by flush.

= = Feature: Get the latest data from the database and synchronize to the entity =================================================
1. Refresh the entity refresh ()--Update from the data table
If the currently managed entity is not the most recent data in the database, you can refresh the entity by using the Refresh () method, which overrides the new value in the database into the entity:
Em. Refresh (obj);
For example:
Student Student = Em.find (Student.class, 1);
If the record in student at this time has changed in the database, you can get the latest data through the Refresh () method:
Em. Refresh (student);


= = Features: Querying data from Entities =========================================================
1. Search entity by primary key find ()--query records from the data table
Once the object is persisted to the database, it produces a primary key, which we can query with this primary key. The method of querying is simple, just to specify the ID to query and the entity class of the object after the query, you can get an instance of the record.
Object obj = Em.find (clazz, id);
Where Clazz is the class name of the entity bean.
There is also a method getreference (), which uses the same method as the Find () method, which throws an exception differently when no records are found in the database.
For example:
Student Student = Em.find (Student.class, 1);
Similar to the following SQL statement executed:
SELECT * from student where id=1;

= = Features: view, detach entity managed by container ====================================================
1, check whether the entity is managed contains ()
The flush () and merge () in the preceding article differentiate between whether the entity is managed by the container, the so-called entity managed by the Entity manager, is not managed, or is not in the scope of the Entity Manager container, i.e. it is not persisted by various operation functions of the entity manager.
The Entity Manager provides a method, contains (), to check whether an entity is managed. The form is as follows:
Boolean B = em.contains (obj);
The contains () method uses an entity as a parameter, or False if the entity object is currently managed by persisted content.
For example:
Student Student = Em.find (Student.class, 1);
if (Em.contains (person)) {
Content management is being persisted
}else{
is not managed by persistent content
}

2, the entity of the separation Management Clear ()
When a large number of entities are processed, these entities will be present in the entity manager, which consumes a lot of memory and slows down the program. If you want to reduce consumption, you can use the clear () method to separate the entities that are being managed from the persisted content. As shown below:
Em.clear ();
If the clear () method is called, any changes previously made to the entity will be lost, so the flush () method is called before the Clear () method is called to save the changes.


Persistent API (JPA) series (iv) Manager entitymanager--performing database updates

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.