JPA learning notes-EntityManager

Source: Internet
Author: User

JPA learning notes-EntityManager
Persistance method 1 for obtaining EntityManagerFactory. pass persistenceUnitName to get 1 EntityManagerFactory entityManagerFactory = Persistence. createEntityManagerFactory (persistenceUnitName); 2.123Map <String, Object> properties = new HashMap <String, Object> (); properties. put ("hibernate. show_ SQL ", false); EntityManagerFactory entityManagerFactory = Persistence. createEntityManagerFactory (persistenceUnitName, properties ); In the JPA specification, EntityManager is the core object for completing persistence operations. As a common Java object, an object becomes a persistent object only when EntityManager is called to persist it. The EntityManager object manages O/R ing between a set of entity classes and underlying data sources. It can be used to manage and update Entity beans. The root token primary key searches for Entity beans, and the Entity can also be queried through JPQL statements. Object status:-New status: the newly created object does not have a persistent primary key. -Persistent State: a persistent primary key has been created and the context environment has been created for persistence.-Free State: a persistent primary key has been created, but the context environment has not been created for persistence.-delete State: a persistent primary key has been created, the context environment has been established with persistence, but is deleted from the database.

Public class JPATest {private EntityManagerFactory entityManagerFactory; private EntityManager entityManager; private EntityTransaction entityTransaction; @ Before public void init () {entityManagerFactory = Persistence. createEntityManagerFactory ("Jpa"); entityManager = entityManagerFactory. createEntityManager (); entityTransaction = entityManager. getTransaction (); entityTransaction. begin () ;}@ Afte R public void destroy () {entityTransaction. commit (); entityManager. clear (); entityManagerFactory. close () ;}// similar to the get method of the session in Hibernate @ Test public void testFind () {// when the find method is executed, an SQL statement is sent to query the database Customer customer = entityManager. find (Customer. class, 1); System. out. println ("-------------------"); System. out. println (customer);} // load method similar to the session in Hibernate @ Test public void testGetRefrence () {C Ustomer customer = entityManager. getReference (Customer. class, 1); System. out. println ("-------------------"); // when the object is actually used, an SQL statement is sent to query the database System. out. println (customer);} // similar to the save method of the session in Hibernate. Unlike the save method, if the object has an id, an exception @ Test public void testPersistence () is thrown when the insert operation is executed differently () {Customer customer = new Customer (); customer. setAge (30); customer. setEmail ("[email protected]"); customer. setLastName ("SS"); enti TyManager. persist (customer); System. out. println (customer. getId (); // The object changes from a temporary state to a persistent State} // similar to the delete method of session in Hibernate, only persistent objects can be removed. The delete method of Hibernate can also remove the free object @ Test public void testDelete () {/** and cannot remove the free object * Customer customer = new Customer (); * customer. setId (2); * entityManager. remove (customer); */Customer customer = entityManager. find (Customer. class, 2); entityManager. remove (customer);} // similar to the saveOrUpdate method of Hibernate Session @ Test public void testMerge1 () {// temporary object, no id Customer customer = new Customer (); customer. setAge (24); customer. setEmail ("[email protected]"); customer. setLastName ("DD"); // creates a new object and copies the properties of the temporary object to the new object, then perform a persistent operation on the new object // The new object has an id, but the previous temporary object does not have the id Customer mermer2 = entityManager. merge (customer); System. out. println (customer); // Customer [id = null, lastName = DD, email = [email protected], age = 24] System. out. println (customer2); // Customer [id = 5, lastName = DD, email = [email protected], age = 24]} @ Test public void testMerge2 () {// free object, with the id attribute // if this object is not found in the EntityManager cache // if no corresponding record exists in the Database // JPA creates a new object, copy the attributes of the current free object to the newly created object // execute the insert operation Customer customer = new Customer (); customer on the newly created object. setAge (24); customer. setEmail ("[email protected]"); customer. setLastName ("DD"); customer. setId (35); Customer customer2 = entityManager. merge (customer); System. out. println (customer); // Customer [id = 35, lastName = DD, email = [email protected], age = 24] // This record is not found in the database. out. println (customer2); // Customer [id = 6, lastName = DD, email = [email protected], age = 24]} @ Test public void testMerge3 () {// free object, with the id attribute // if this object is not found in the EntityManager cache // if there is a corresponding record in the database // JPA queries the corresponding record, return the object corresponding to the record, and copy the attributes of the Free object to the queried object. // execute update Customer customer Customer = new customer (); Customer on the queried object. setAge (23); customer. setEmail ("[email protected]"); customer. setLastName ("DD"); customer. setId (7); Customer customer2 = entityManager. merge (customer); System. out. println (customer); // Customer [id = 6, lastName = DD, email = [email protected], age = 23] System. out. println (customer2); // Customer [id = 6, lastName = DD, email = [email protected], age = 23]} @ Test public void testMerge4 () {// free object, has the id attribute // if the object is cached in EntityManager // JPA copies the attribute of the Free object to the cached object // then executes update Customer customer = new Customer on the cached object (); customer. setAge (23); customer. setEmail ("[email protected]"); customer. setLastName ("DD"); customer. setId (7); Customer customer2 = entityManager. find (Customer. class, 7); // The cache contains the entityManager object whose id is 7. merge (customer); System. out. println (customer = customer2); // false} // The flush method of the session in Hibernate @ Test public void testFlush () {Customer customer = entityManager. find (Customer. class, 6); System. out. println (customer); customer. setLastName ("shang"); entityManager. flush (); // refresh the database and force update }}

 

Other methods of EntityManager flush (): Synchronize the persistent context to save the state information of all objects not saved in the persistent context to the database. SetFlushMode (FlushModeTypeflushMode): sets the Flush mode of the persistent context. The parameter can take two enumerations-FlushModeType. AUTO is used to automatically update the database entity, and-FlushModeType. COMMIT is used to update the database records until the transaction is committed. GetFlushMode (): gets the Flush mode of the persistent context. Returns the enumerated value of the FlushModeType class. Refresh (Objectentity): updates the state of the object with the value recorded by the database entity, that is, updates the attribute value of the instance. Clear (): clears the persistent context and disconnects all associated entities. If there are any unsubmitted updates, they will be revoked. Contains (Objectentity): determines whether an instance belongs to an object managed by the current persistent context. IsOpen (): checks whether the current Entity Manager is open. GetTransaction (): returns the transaction object of the resource layer. The EntityTransaction instance can be used to start and submit multiple transactions. Close (): close the Entity Manager. If you call the method of the Object Manager instance or the method of its derived query object, the IllegalstateException will be thrown, except the getTransaction and isOpen methods (false is returned ). However, when the transaction associated with the Entity Manager is active, the persistent context will remain in the managed State after the close method is called until the transaction is completed. EntityTransactionEntityTransaction interface is used to manage the transaction operations of the resource layer Entity Manager. Obtain the instance by calling the getTransaction method of the Object Manager. Begin ()-used to start a transaction. Subsequent database operations will be committed or withdrawn as a whole. If the transaction is started, an IllegalStateException is thrown. Commit ()-used to submit the current transaction. All database update operations after the transaction is started are persistent to the database. Rollback ()-Undo (rollback) The current transaction. That is, all database update operations after the transaction is started are withdrawn without affecting the database. SetRollbackOnly ()-the current transaction can only be undone. GetRollbackOnly ()-check whether the Undo flag is set for the current transaction. IsActive ()-check whether the current transaction is active. If true is returned, the begin method cannot be called. Otherwise, an IllegalStateException exception is thrown. If false is returned, the commit, rollback, setRollbackOnly, and getRollbackOnly methods cannot be called. Otherwise, an IllegalStateException is thrown.

Related Article

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.