JPA Learning Notes (5)--entitymanager related

Source: Internet
Author: User

    • Persistence
    • Entitymanagerfactory
    • Entitymanager
      • Find method
      • GetReference method
      • Persist method
      • Remove method
      • Merge method
        • Case 1 The Incoming object has no ID
        • Scenario 2 An incoming object has identitymanager in the cache without that record in the object database
        • Scenario 3 An incoming object has a Identitymanager cache without that record in the object database
        • Scenario 4 An Incoming object has a Identitymanager cache for that object
      • Flush method
      • Refresh method
      • Clear
      • Contains Object entity
      • IsOpen
      • Gettransaction
      • Close
      • CreateQuery String qlstring
      • Createnamedquery String Name
      • Createnativequery String sqlString
      • Createnativequery string Sqls string resultsetmapping

Persistence

In previous JPA learning notes (2)--Create a JPA project with the use of persistence to create entitymanagerfactory instances

String"jpa"; EntityManagerFactory factory = Persistence.createEntityManagerFactory(persistenceUnitName);

In fact, it also has an overloaded method available

Map<StringObjectnew HashMap<StringObject>();properties.put("hibernate.format_sql"false);EntityManagerFactory factory= Persistence.createEntityManagerFactory(persistenceUnitName,properties);

The properties here are the same as those in configuration file Persistence.xml.

Entitymanagerfactory

The Entitymanagerfactory interface is primarily used to create Entitymanager instances. The interface contracts the following 4 methods:

    1. Createentitymanager (): Used to create an instance of an entity manager object.

    2. Createentitymanager (Map map): An overloaded method for creating an instance of an entity manager object, which is used to provide Entitymanager properties.

    3. IsOpen (): Check if Entitymanagerfactory is open. The Entity Manager factory is open until it is created, unless the close () method is called to close it.

    4. Close (): Entitymanagerfactory off. All resources will be freed after Entitymanagerfactory is closed, the IsOpen () method test will return false, other methods will not be called, otherwise the illegalstateexception exception will be caused.

Entitymanager

The following code omits the creation of the entitymanager,entitymanagerfactory,transaction, the closing process, etc.

Find method
//查询ID为1的OrderOrderorder = entityManager.find(Order.class1);
GetReference method
Order order = entityManager.getReference(Order.class1);System.out.println("-------------------------------------");System.out.println(order);

The use of this method is the same as find (), but there are some differences, look at the results below:

In the code, I first call getreference and then print "-----" and finally print the order object

But from the perspective of printing "----", then query order, and then print order.

Cause: Calling the GetReference () method, the return is not actually an order object, but rather a proxy. When you want to use order, the query statement is actually invoked to query the order object

Persist method
OrderordernewOrder();order.setOrderName("hehe");entityManager.persist(order);System.out.println("id="+order.getId());

Performs an insert operation, equivalent to the Save () method of Hibernate

As you can see from the code above, we don't give the order an ID, but after executing the persist method, there is no query from the database, and Order.getid () can also get the value. This is also a feature of the persist method: Making an object from a temporary state into a persisted state.

Results:

However, it is somewhat different from Hibernate's Save () method: If an object has an ID, it cannot perform an insert operation and throws an exception

Remove method

The delete () method equivalent to hibernate, but somewhat different:

The Remove () method cannot remove a free object, only the persisted object, what does it mean? Compare the following two sections of code:

OrderordernewOrder();order.setId(140);entityManager.remove(order);

The above code throws an exception because order is an object that we create ourselves, that is, a free object.

It must be written like this:

OrderordernewOrder();order = entityManager.find(Order.class140);entityManager.remove(order);

The order in this code is obtained from the database, that is, the persisted object

Hibernate's Delete () method, as long as the object has an ID, you can delete

Merge method Case 1: The incoming object has no ID
OrderordernewOrder();order.setOrderName("hehe");Order order2 = entityManager.merge(order);System.out.println("order2#id:"+order2.getId());

Conclusion: In this case, the merge method is called, a new object (with ID) is returned and an insert operation is performed on the new object.

Scenario 2: The object is not in the Id,entitymanager cache in the incoming object, there is no record in the database
OrderordernewOrder();order.setId(1000);order.setOrderName("hehe");Order order2 = entityManager.merge(order);System.out.println("order#id:"+order.getId());System.out.println("order2#id:"+order2.getId());

Conclusion: In this case, the merge method is called, a new object is returned and an insert operation is performed on the object. The ID of the new object is the ID of the record in the database (such as the self-growing ID), not the ID that we passed in. (In fact, the result is the same as in the case 1)

Scenario 3: The incoming object has a Id,entitymanager cache without the object, the record is in the database
OrderordernewOrder();order.setId(170);order.setOrderName("wahahahahah");Order order2 = entityManager.merge(order);System.out.println("order:"+order);System.out.println("order2:"+order2);

Pre-call database table:

Result after call:

Conclusion: In this case, the merge method is called, the corresponding record is queried from the database, a new object is generated, the object that we passed in is copied to the new object, and the update operation is performed last. In simple terms, it's the update operation

Scenario 4: An incoming object has a Id,entitymanager cache for that object
Order Order = New Order();Order.SetId ( the);Order.Setordername ("Xixixixi");//Read the object into the Entitymanager cache via findOrderOrder3=Entitymanager.FindOrder.Class the);OrderOrder2=Entitymanager.MergeOrder); System.Out.println"Order:"+Order); System.Out.println"Order2:"+ORDER2);

The result is the same as in case 3.

Conclusion: In this case, calling the merge method, JPA assigns the incoming object to the object in the Entitymanager cache, and then performs an update operation on the object in the Entitymanager cache. (as is the case with the result of 3)

Flush method

To view the database first, there is a record as follows:

Then execute the following code

Order order= entityManager.find(Order.class170);System.out.println("order:"+order);order.setOrderName("bbb");//5. 提交事务transaction.commit();

View results:

The result is that JPA actually performed the update operation and changed the AAA to BBB, but in the code we did not perform the update operation.

Cause: Order is queried through the Find method, so it is persisted, that is, it is cached in Entitymanager, and when the transaction commits, the cache is updated to the database.

The Flush method, however, forces the cache to be updated to the database

entityManager.flush();

Related to:

    • Setflushmode (Flushmodetype Flushmode): Sets the flush mode for a persistent context environment. Parameter can take 2 enumerations

      • Flushmodetype.auto to automatically update database entities,
      • Flushmodetype.commit The database record is not updated until the transaction is committed.
    • Getflushmode (): Gets the flush mode of the persistence context. Returns an enumeration value for the Flushmodetype class.

Refresh method
Orderorder= entityManager.find(Order.class170);order= entityManager.find(Order.class170);

Running the above code, it was found that two times find was called, but only once the SELECT statement was executed, which was caused by the cache.

Then look at the following code:

Orderorder= entityManager.find(Order.class170);entityManager.refresh(order);

The Find method was called only once, but two times the SELECT statement was executed because the Refresh method went to see if the data state in the cache was consistent with the database, so a SELECT statement was executed again

Clear ()

Clears the persistent context environment and disconnects all associated entities. If there are uncommitted updates at this time, they will be undone.

Contains (Object entity):

Determines whether an instance belongs to an entity that is currently managed by a persistent context environment.

IsOpen ()

Determines whether the current entity manager is open.

Gettransaction ()

Returns the transaction object for the resource layer. Entitytransaction instances can be used to start and commit multiple transactions.

Close ()

Close the entity manager. Subsequent methods that call the Entity Manager instance or its derived query object will throw illegalstateexception exceptions, except for the Gettransaction and IsOpen methods (return False). However, when the transaction associated with the entity manager is active, the persistence context is still in the managed state until the transaction completes when the Close method is called.

CreateQuery (String qlstring)

Creates a query object.

Createnamedquery (String name)

Creates a query object based on a named query statement block. The parameter is a named query statement.

Createnativequery (String sqlString)

Create a Query object using standard SQL statements. parameter is a standard SQL statement string.

Createnativequery (String sqls, String resultsetmapping)

Creates a query object using standard SQL statements and specifies the name of the map that returns the result set.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JPA Learning Notes (5)--entitymanager related

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.