Persistence context

When we have multiple persistence units defined in the persistence.xml file, we need to inject the appropriate one to EntityManager using the @PersistenceContext annotation. We can point to a specific persistence unit using the PersistenceContext entity's unitName attribute.

Using @PersistenceContext on EntityManager, let's point to the integration unit:

@Stateless
class App {
@Inject
private lateinit var identityCreator: IdentityCreator
@PersistenceContext(unitName = "integration")
private lateinit var entityManager: EntityManager

fun createIdentity(inputData: InputData): Person {
val person = identityCreator.createPerson(inputData)
entityManager.persist(person)
return person
}

fun findAllPerson(): List<Identity> {
return
entityManager.createNamedQuery(Queries.FIND_ALL_PERSON,
Person::class.java).resultList
}
}

Using unitName = "integration", we point to a persistence unit in the integration environment. We can point to different persistence units as follows:

@Stateless
class App {
@Inject
private lateinit var identityCreator: IdentityCreator
@PersistenceContext(unitName = "production")
private lateinit var entityManager: EntityManager

fun createIdentity(inputData: InputData): Person {
val person = identityCreator.createPerson(inputData)
entityManager.persist(person)
return person
}

fun findAllPerson(): List<Identity> {
return
entityManager.createNamedQuery(Queries.FIND_ALL_PERSON,
Person::class.java).resultList
}
}
When we have only one database, we don't actually have to configure the persistence unit for entity manager injection. In this case, the default persistence unit defined in the persistence.xml file will be used. This is shown in the following code snippet:
<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_2_0.xsd"
version="2.0">

<persistence-unit name="local" transaction-type="JTA">
<jta-data-source>jdbc/local_datasource</jta-data-source>
<properties>
<property name="javax.persistence.schema-
generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>

On the other hand, our application server has to be configured with the connection details for the specific data source. 

In this section, we have learned how to configure our application to use the persistence context and the persistence units of the specific data sources.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset