In our JPA HelloWorld, we saw a simple JPA save operation, so let's take a good look at some of the major JPA classes
1. Basic several classes:
The ①:persistence class is used to get the entitymanagerfactory instance. The class contains a static method named Createentitymanagerfactory. There are two overloaded versions of the Createentitymanagerfactory method. a method with a parameter with the persistence unit name parameter in the JPA configuration file Persistence.xml We configured a persistence.xml name in front of Meta-inf:
<persistence-unit name= "Jpa-1" transaction-type= "resource_local" >
。 A method with two parameters : the previous parameter has the same meaning, and the latter parameter, the map type, is used to set the related properties of the JPA, ignoring the properties set elsewhere (as set in the configuration file). The property name of the Map object must be the property name of the JPA implementation Library provider's namespace convention. For example:
map<string,object> map=New hashmap<string,object>(); Map.put (true); Factory=persistence.createentitymanagerfactory ("Jpa-1", map);
The ②entitymanagerfactory:entitymanagerfactory interface is primarily used to create Entitymanager instances. The interface has the following 4 methods: Createentitymanager (): Used to create an instance of the entity Manager object. Createentitymanager (Map map): An overloaded method for creating an instance of an entity manager object, which is used to provide Entitymanager properties. 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. 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.
③ in the JPA specification, Entitymanager is the core object to complete the persistence operation. An entity is a normal Java object that becomes persisted only when the entitymanager is called to persist it. The Entitymanager object manages the O/R mapping between a set of entity classes and the underlying data source. It can be used to manage and update entity beans, find the entity bean by the primary key, and query entities through the JPQL statement. Entity state: New state: The newly created object, which does not already have a persistent primary key. Persistent state: A persistent primary key has been established and persisted to establish a context Free State: A persistent primary key, but no context removal state with persistence: having a persisted primary key, the context is established and persisted, but deleted from the database.
Here are some tests of the above classes:
Package Com.hotusm.common.test;import Javax.persistence.entitymanager;import Javax.persistence.entitymanagerfactory;import Javax.persistence.entitytransaction;import Javax.persistence.persistence;import Org.junit.after;import Org.junit.before;import Org.junit.Test;import Com.hotusm.commom.entity.User; Public classTestapi {entitymanagerfactory factory; Entitymanager em; Entitytransaction et; @Before Public voidInit () {Factory=persistence.createentitymanagerfactory ("Jpa-1"); EM=Factory.createentitymanager (); ET=em.gettransaction (); Et.begin (); } @Test Public voidSave () {User User=NewUser (); User.setdesc ("Mans"); User.setname ("HOTUSM"); Em.persist (user); } @After Public voiddestory () {et.commit (); Em.close (); Factory.close (); }}
2 Persistence methods: For persisted operations are performed using Entitymanager
Find (class<t> entityclass,object primaryKey): Returns the entity class object corresponding to the specified OID, and returns a cached object if the entity exists in the current persisted environment Otherwise a new Entity is created and the relevant information in the database is loaded and a null is returned if the OID does not exist in the database. The first parameter is the entity class type being queried, and the second parameter is the primary key value of the entity to be found.
getreference (class<t> entityclass,object primaryKey): Similar to the Find () method, unlike: If the specified Entity does not exist in the cache, Entitymanager creates a proxy for the entity class, but does not immediately load the information in the database, only the first property that actually uses the entity is loaded, so if the OID does not exist in the database, getreference () does not return a null value, but Throw Entitynotfoundexception These two methods are similar to hibernate in the Session.get and Session.load two methods, because of the reason of proxy object, so in some cases, will throw lazy loading situation,
persist (Object entity): used to incorporate newly created entity into Entitymanager management. After the method executes, the Entity object passed into the persist () method is converted to a persisted state. If the Entity object that passed in the persist () method is already persisted, the persist () method does nothing. If the persist () operation is performed on an Entity that deletes a state, it is converted to a persisted state. If the persist () operation is performed on an entity that is free, the persist () method may throw a entityexistexception (or it may be thrown after flush or transaction commit).
Remove (Object entity): deletes the instance. If the instance is managed, which is associated with a database entity record, the associated database record is also deleted.
merge (T entity):merge () is used to process entity synchronization. That is, the database insert and update operations, This method is similar to the Sesson.saveorupdate method in hibernate, but there are a few different places, if you save a temporary object, then before persisting, Entitymanager will first create a first object, and then copy the properties of the free object into the new object. , and finally the newly created object is persisted. If it is a free object, then another kind of operation, the following is the specific diagram:
Entitymanager a few other methods:
Refresh (object entity): updates the state of the entity object with the value of the database entity record, that is, the property value of the instance is updated. 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 managed by the current persistence context. 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 (): Closes 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): Creates 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.
3EntityTransaction
The Entitytransaction interface is used to manage transaction operations for the resource-level entity manager. The instance is obtained by invoking the Gettransaction method of the entity manager.
Begin () is used to start a transaction, after which multiple database operations are committed or undone as a whole. A IllegalStateException exception is thrown if the transaction is started. Commit () is used to commit the current transaction. All database update operations after the start of the transaction are persisted to the database. Rollback () undoes (rolls back) the current transaction. That is, all database update operations after the start of the transaction are undone, thereby not affecting the database. Setrollbackonly () causes the current transaction to be undone only. Getrollbackonly () to see if the current transaction is set to only undo flags.
IsActive () to see if the current transaction is active. If true, the Begin method cannot be called, otherwise the illegalstateexception exception will be thrown, and if False is returned, commit, rollback, setrollbackonly, and The Getrollbackonly method, or the illegalstateexception exception will be thrown.
JPA Learning (3) JPA API