Entitymanager Use method API function to explain __ function

Source: Internet
Author: User

Actions of the session bean or MD bean to the entity bean include all query insert update Delete operations that are done through Entitymanager instances Entitymanager are created by EJB Containers are automatically managed and configured without the need for the user to create themselves please note that the entity Bean is managed by Entitymanager Entitymanager will track his state changes when any decision is made to update the entity bean, the changed value is synchronized Same as hibernate in the database. But if entity beans are separated from entitymanager, he is not managed Entitymanager cannot track any state changes 1get entity Find or GetReference 2insert persist 3update 2 cases the working rule of the container when the Emmergeperson method is executed 4Delete Remove 5HPQL query createquery 7Refresh entity Refresh 8Ch Eck entity whether in Entitymanager Management contains 9 detach all entities that are currently being managed clear 10 refreshes the entity changes immediately into the database flush 11 Change the flush mode of the entity manager Setflushmode 12 Gets the reference getdelegate of the persistent implementation

Session Bean or MD bean operations on the Entity Bean (including all query, insert, UPDATE, Delete operations are done by Entitymanager instances. Entitymanager are automatically managed and configured by the EJB container and do not need to be created by the user themselves.

So how does the session bean or MD Bean get the Entitymanager instance ...
Very simply, the following code is used for dependency injection:

public class sessionbean1{
    @PersistenceContext
    entitymanager em;
...
}

Note: If multiple persistence-unit are configured in the Persistence.xml file, the persistent name must be specified when the Entitymanager object is injected. specified by the Unitname property of the @persistencecontext annotation, for example:

@PersistenceContext (unitname= "Foshanshop")
entitymanager em;

If there is only one persistence-unit, you do not need to specify it explicitly. Note that when the Entity Bean is Entitymanager managed, Entitymanager tracks his state changes and synchronizes the changed values into the database (like hibernate) whenever a decision is made to update the entity bean. However, if the entity bean is separated from Entitymanager, he is not managed, and Entitymanager cannot track any changes in his state.

Entitymanager Some common APIs (including query, insert, UPDATE, delete operations) 1) Get Entity--find () or getreference ()

Person person = em.find (person.class,1);

When a record is not found in the database, GetReference () and find () are different, and the Find () method returns NULL, while GetReference () Method throws the javax.persistence.EntityNotFoundException exception, and the GetReference () method does not guarantee that the entity bean has been initialized. If the argument passed into the getreference () or find () method is not an entity bean, IllegalArgumentException exception 2 is raised insert--persist ()

person who = new person ();
Person.setname (name);
Save the data into the database
em.persist (person);

If the argument passed into the persist () method is not an entity bean, the illegalargumentexception is raised
3) update--divided into 2 kinds of casesSituation 1: When the entity is being managed by the container, you can invoke the entity's set method to modify the data, and when the container determines the flush (which is determined by the container), the updated data is synchronized to the database, rather than being synchronized to the database immediately after the set method is invoked to modify the data. If you want the modified data to be synchronized to the database immediately, you can call the Entitymanager.flush () method.
public void Updateperson () {
    try {person person
        = Em.find (Person.class, 1);
        Person.setname ("lihuoming"); The data can be updated after the method has been executed
    (Exception e) {
        e.printstacktrace ();
    }
}
Scenario 2: When the entity Bean is already out of Entitymanager management, the set method that you invoke the entity to modify the data cannot be synchronized to the database. You must call the Entitymanager.merge () method. After the call, the updated data is synchronized to the database when the container determines flush (this is determined by the container). If you want the modified data to be synchronized to the database immediately, you can call the Entitymanager.flush () method.
public boolean Updateperson (person person) {
    try {
        em.merge (person);
    } catch (Exception e) {
        E.printstacktrace ();
        return false;
    }
    return true;
}

The following code invokes the above method. Because the following second line of code returns the entity bean to the client, the entity bean has been left out of the container's management, the entity bean modified at the client, and finally returned to the EJB container for the update operation:

Persondao Persondao = (Persondao) ctx.lookup ("Persondaobean/remote");
Person person = Persondao.getpersonbyid (1); At this time the person has been separated from the management of the container
person.setname ("Zhangxiaoyan");
Persondao.updateperson (person);
work rules for a container when the Em.merge (person) method is executed:

1 if a container-managed person instance with the same ID already exists in the container, the container will copy the contents of the parameter person into the managed instance, the merge () method returns the managed instance, but the parameter person is still detached and is not managed. The container synchronizes the instance into the database when determining flush.

There is no person instance with the same ID in the 2 container. The container will copy a container-managed person instance based on the passed in person parameter while the merge () method returns the managed instance, but the parameter person is still detached and is not managed. The container synchronizes the instance into the database when determining flush.

If the argument passed into the merge () method is not an entity bean, a illegalargumentexception is raised. 4) Delete--remove ()

Person person = Em.find (Person.class, 2);
If the cascade relationship is Cascade=cascadetype.all, the cascading object is deleted when the person is deleted.
Setting the Cascade property to Cascade=cascadetype.remove has the same effect.
Em.remove (person);

If the argument passed into the Remove () method is not an entity bean, a illegalargumentexception 5 hpql query--createquery () is thrown.

In addition to using the Find () or getreference () method to get the entity bean, you can also get the entity bean through JPQL.

To execute the JPQL statement, you must create a query object through the Entitymanager createquery () or Createnamedquery () method

Query query = em.createquery ("Select p from Person p where p. name= ' Dawn");
List result = Query.getresultlist ();
Iterator iterator = Result.iterator ();
while (Iterator.hasnext ()) {
    //process person
}
...
Execute UPDATE statement
query query = em.createquery ("Update person as P set p.name =?1 where p. personid=?2");
Query.setparameter (1, "Dawn");
Query.setparameter (2, New Integer (1));
int result = Query.executeupdate (); Number of records affected
...
Execute UPDATE statement
query query = em.createquery ("Delete from person");
int result = Query.executeupdate (); Number of records affected

6) SQL Query--createnaivequery ()
Note: This method is for SQL statements, not HPQL statements

We can let the EJB3 persistence the running environment populate the column values directly into a entity instance,
//And return the instance as the result.
Query query = em.createnativequery ("SELECT * from person", person.class);
List result = Query.getresultlist ();
if (result!=null) {
    iterator iterator = Result.iterator ();
    while (Iterator.hasnext ()) {person person= (person
        ) Iterator.next ();
    .. 
    }}
... Execute UPDATE statement directly through SQL
query query = em.createnativequery ("Update person set age=age+2");
Query.executeupdate ();
7) Refresh Entity--refresh ()

If you suspect that the currently managed entity is not the most recent data in the database, you can refresh the entity with the Refresh () method, and the container will rewrite the new value in the database into the entity. This usually happens after you get the entity, someone updates the records in the database, and you need to get the latest data. Of course, you can also get the latest data by calling the Find () or GetReference () method again, but this is not elegant.

Person person = Em.find (Person.class, 2);
If the record for person in this case has changed in the database,
//You can get the latest data through the Refresh () method.
Em.refresh (person);
8 Check entity whether in Entitymanager Management--contains ()

The contains () method uses an entity as an argument, or False if the entity object is currently being managed by persisted content and the return value is true. If the passed parameter is not an entity Bean, a illegalargumentexception is raised.

Person person = Em.find (Person.class, 2);
...
if (Em.contains (person)) {//is being
persisted content management
}else{
//is no longer managed by persistent content
}
9 Separation of all entities currently being managed--clear ()

When dealing with a large number of entities, if you do not separate the processed entities from the Entitymanager, you will consume a lot of memory. After the Entitymanager clear () method is invoked, all entities being managed will be detached from the persisted content. One thing to note is that before a transaction is committed without committing it (the transaction defaults to the end of the call stack, such as: The Return of the method, if the clear () method is invoked, any previous changes to the entity will be lost, so it is recommended that you call the flush () method to save the changes before calling the clear () method. 10 Change the entity changes immediately to the database--flush ()

When the Entitymanager object is used in a session bean, it is bound to the transaction context of the server. Entitymanager commits and synchronizes the contents of a server when it commits a transaction. In one session bean, the transaction of the server is defaulted to the end of the call stack (for example, the return of a method).

Example 1: Committing a transaction only when the method returns

public void Updateperson (person person) {
    try {person person
        = Em.find (Person.class, 2);
        Person.setname ("lihuoming");
        Em.merge (person);
        There are also a number of modify operations
    } catch (Exception e) {
        e.printstacktrace ();
    }
    The update will be committed and flushed to the database at the end of this method
}

In order to update changes to the database only when the transaction is committed, the container centralizes all database operations in one batch, reducing costly interaction with the database. When you call persist (), merge () or remove () These methods, updates are not immediately synchronized to the database until the container decides to flush into the database, and by default the container determines whether the refresh occurs before the related query executes or when the transaction is committed, of course, "related queries" In addition to find () and getreference (), these two methods do not cause the container to trigger the refresh action, the default refresh mode can be changed, please refer to the section below.

If you need to refresh the update to the database before the transaction is committed, 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.

public void Updateperson (person person) {
    try {person person
        = Em.find (Person.class, 2);
        Person.setname ("lihuoming");
        Em.merge (person);
        Em.flush ()//manually refresh the update immediately into the database

        //followed by numerous modification operations
    } catch (Exception e) {
        e.printstacktrace ();
    }
}
11) Change the flush mode of the Entity Manager--setflushmode ()

There are 2 types of flush modes: AUTO and COMMIT. Auto is the default mode. You can change his value as follows:
Entitymanager.setflushmode (Flushmodetype.commit);

Flushmodetype.auto: Refresh occurs before the query statement executes (except find () and getreference () queries) or transaction commits: There are no query statements in the process of updating data (except find () and getreference () query) execution .

Flushmodetype.commit: Refresh occurs only when a transaction is committed: the execution of a query statement (except find () and getreference () query) in the process of updating data in large quantities.

In fact, the result of the above two modes is: the number of times the JDBC driver interacts with the database. The greatest improvement in JDBC performance is to reduce the network traffic between the JDBC driver and the database. The Flushmodetype.commit mode causes the update to be done only once in a network interaction, while the Flushmodetype.auto pattern may require multiple interactions (how many times the flush has been triggered) 12) to obtain a reference to the persistent implementation- -getdelegate ()

Using the Getdelegate () method, you can obtain a reference to the Entitymanager persistence provider, such as JBoss EJB3 's persistence product using Hibernate, which can be accessed through the Getdelegate () method, such as:
Hibernateentitymanager manager = (Hibernateentitymanager) em.getdelegate ();

After obtaining a reference to the hibernate, you can encode it directly against the hibernate, but this method is not advisable and is strongly recommended for use. In WebLogic, you can also get access to Kodo in this way.

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.