The method of entityManager find the difference between JPA and methods getReference

Scenes

Introduction to JPA and build HelloWorld (with code to download):

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103473937

Note:

Blog home page:
https://blog.csdn.net/badao_liumang_qizhi
public concern number of
programs overbearing ape
acquisition-related programming e-books, tutorials and push for free download.

achieve

find

Returns the OID corresponding entity class object, if the entity exists in the current persistent environment, a cached object is returned; otherwise it will create a new Entity, and load the database information; if the OID does not exist in the database in a null is returned. The first entity class parameter type is a query, the second parameter is the primary key to be searched entities.

getReference

And find () method is similar, except that: If the specified Entity does not exist in the cache, EntityManager creates an Entity class of agents, but does not immediately load the information in the database, only the first real use of the properties of this Entity before loaded, so if this does not exist in the database OID, getReference () does not return a null value, but throw EntityNotFoundException

unit test

Test method find

@Test
public void testFind() {
 Customer customer = entityManager.find(Customer.class, 3);
 System.out.println("-------------------------------------");
  
 System.out.println(customer);
}

 

Test Results

Test method getReference

@Test
public void testGetReference(){
 Customer customer = entityManager.getReference(Customer.class, 3);
 System.out.println(customer.getClass().getName());  
 System.out.println("-------------------------------------");  
 System.out.println(customer);
}

 

Through the above tests found

find method is similar to the hibernate Session get method.

getReference method is similar to hibernate method Session of the load.

find () made a select operation, but did not do getReference operations related to the database, but returns a proxy, so that it reduces the cost of connecting to the database and load the persistent state from the database.


 

Guess you like

Origin www.cnblogs.com/badaoliumangqizhi/p/12017128.html