1. In the container, entitymanager is managed by the container, and its transactions are managed by JTA. When entitymanager is called, the container first checks whether it is in the persistent context.
If yes, entitymanager uses the persistent context and associated transactions;
If no persistence context is associated, a new persistence context is created and the entitymanager is associated with the transaction.
2. The persistence context of the entitymanager managed by the container has two scopes:
(1) Transaction type
By default, stateless session beans are all in transaction units.
By default, Session Bean uses a persistent context in the unit of a transaction.
By default, a method in bean is a transaction.. ----- A method is the scope of action of a persistent context.
A persistence context is established in a general transaction method. When a transaction ends, the persistence context ends.
(2) extended type
The stateless Session Bean creates a new persistent context each time it is called. In the stateful Session Bean, the client needs to save the customer information, even if multiple calls are required.
In the same persistent context, set the persistence context type to extended.
@ Persistencecontext (Type = persistencecontexttype. Extended)PrivateEntitymanager em;PrivateCustomer customer;Public VoidInit (integer customerid) {customer = em. Find (customer.Class, Customerid );}Public VoidPlaceorder (integer customerid, order ){// The same persistent context as the init method. All methods that can be directly used by the customerCustomer. getorders (). Add (order); em. Merge (customer );}
Bytes ------------------------------------------------------------------------------------------------------------------------
Configure persistence. xml
<? XML version = "1.0" encoding = "UTF-8" ?> < Persistence Xmlns = Http://java.sun.com/xml/ns/persistence" Xmlns : Xsi = Http://www.w3.org/2001/XMLSchema-instance" Xsi : Schemalocation = Http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" Version = "1.0" > < Persistence - Unit Name = "Bookstorepu" Transaction - Type = "JTA" > < JTA - Data -Source > Java:/JPA </ JTA -Data-Source > < Properties > < Property Name = "Hibernate. dialect" Value = "Org. hibernate. dialect. mysqldialect" /> < Property Name = "Hibernate. hbm2ddl. Auto" Value = "Create-drop" /> < Property Name = "Hibernate. show_ SQL" Value = "True" /> < Property Name = "Hibernate. format_ SQL" Value = "True" /> </ Properties > </ Persistence -Unit > </ Persistence >