Reputation: 11251
I am looking into this EntityManager tutorial and I understood that you either can describe your EM
in persistence.xml
or use annotations.
So I created something similar to this class:
package org.superbiz.injection.jpa;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import java.util.List;
@Stateful
public class Movies {
@PersistenceContext(unitName = "movie-unit", type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;
public void addMovie(Movie movie) throws Exception {
entityManager.persist(movie);
}
public void deleteMovie(Movie movie) throws Exception {
entityManager.remove(movie);
}
public List<Movie> getMovies() throws Exception {
Query query = entityManager.createQuery("SELECT m from Movie as m");
return query.getResultList();
}
}
I got exception:
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: JBAS011047: Component class com.epam.rudenkov.controller.BookStore for component com.epam.rudenkov.controller.BookStore has errors:
JBAS011440: Can't find a persistence unit named movie-unit in deployment \"book_store.war\""}}
Questions:
persistence.xml
?unitName
? Upvotes: 0
Views: 4602
Reputation: 19000
and I understood that you either can describe your EM in persistence.xml or use annotations.
This is not accurate. You configure a persistence context - which is used to construct an EntityManagerFactory - via persistence.xml. As it name suggests, it is a factory for creating Entity Manager instances.
You inject a persistence context (EntityManager) into an EJB via the @PersistenceContext
annotation.
Should I create also persistence.xml?
Yes, this is mandatory when using JBoss AS.
From the WildFly 8 JPA Reference Guide (but generally applicable):
The persistence.xml contains the persistence unit configuration (e.g. datasource name) and as described in the JPA 2.0 spec (section 8.2), the jar file or directory whose META-INF directory contains the persistence.xml file is termed the root of the persistence unit. In Java EE environments, the root of a persistence unit must be one of the following (quoted directly from the JPA 2.0 specification):
What is for unitName?
(Optional) The name of the persistence unit as defined in the persistence.xml file. If the unitName element is specified, the persistence unit for the entity manager that is accessible in JNDI must have the same name.
So you must have something such as <persistence-unit name="movie-unit">
in persistence.xml.
Note that if you have a single persistence unit configured, unitName
is not mandatory.
Upvotes: 2
Reputation: 11
You can describe your mappings in mapping.xml (not persistence.xml) file or use annotations.You need persistence.xml information to create entity manager. "unitName" refers to the "name" attribute of persistence-unit in persistence.xml file.
Upvotes: 0