In my Spring+JPA/Hibernate+Wicket app, I have a QueryBuilder bean that I want to use in one of my DAOs which generates a typed query with the help of Criteria API:
#Service(value="inboxQueryBuilder")
public class InboxQueryBuilder {
#PersistenceContext
EntityManager em;
CriteriaBuilder cb;
public InboxQueryBuilder() {
cb = em.getCriteriaBuilder();
}
public TypedQuery<App> getQueryForApps(AppSearchObject aso) {
...
}
...
}
However, when I run the app, I get a null pointer exception for line:
cb = em.getCriteriaBuilder();
i.e. the EntityManager doesn't get injected. Do you know why?
Also, is this use correct and thread-safe or should I instantiate my InboxQueryBuilder for each query? In that case, should I also inject the EntityManager or should I just pass it as a constructor parameter (the InboxQueryBuilder would get instantiated for each query in the DAO which has an injected instance of EntityManager)?
You can't access the EntityManager within the constructor. Take a look at the #PostConstruct-Annotation
#Service(value="inboxQueryBuilder")
public class InboxQueryBuilder {
#PersistenceContext
EntityManager em;
CriteriaBuilder cb;
public InboxQueryBuilder() {
// em= null
}
#PostConstruct
public void toSomething(){
// em set by Container
cb = em.getCriteriaBuilder();
}
public TypedQuery<App> getQueryForApps(AppSearchObject aso) {
...
}
...
}
EDIT:
After reading your post again, I start to became unsure, if I'm right. I know the Java EE-Dependency-Injection within a JBoss works as I described, but I'm not sure about spring-IOC.
Do you have this bean somewhere in your application context?
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="myPersistenceUnit"/>
</bean>
Spring uses the Java Beans mechanism, so I am pretty sure this is insufficient:
#PersistenceContext
EntityManager em;
Here's the standard way:
private EntityManager entityManager;
#PersistenceContext
public void setEntityManager(final EntityManager entityManager){
this.entityManager = entityManager;
}
Related
I would like to know which way is the best to define entity manager. I am using spring boot
case 1) creating in spring service class like follows
#Service
#Transactional
public class DemoService {
private static final Logger log = LoggerFactory.getLogger(DemoService.class);
private EntityManagerFactory emf;
public void getEntity(){
final EntityManager em = emf.createEntityManager();
}
#PersistenceUnit
public void setEntityManagerFactory(final EntityManagerFactory emf) {
this.emf = emf;
}
}
Case 2.) Define a global entity manager and share it across all services.
Note : Each service only reflects one single Entity definition.
Injecting the EntityManager is the simplest and the most effective way to do it:
#PersistenceContext(unitName = "persistenceUnit")
private EntityManager entityManager;
You don't need to set the EntityManagerFactory, since you need a transaction-bound EntityManager.
You don't need to hold the EntityManager in a global component, since that would be yet another indirection layer and you can simply mock the EntityManager anyway.
I'm trying to get CDI (with Open Web Beans) working from within a unit test using Delta Spike (#RunWith(CdiTestRunner.class)). Dependency injection is working fine but my EntityManagerFactory is always null:
public class EntityManagerProducer {
#PersistenceContext(unitName = "sbPersistenceUnit")
private EntityManagerFactory emf; //Always null
#Produces
public EntityManager create() {
return emf.createEntityManager();
}
public void close(#Disposes EntityManager em) {
if (em.isOpen()) {
em.close();
}
}
}
I know that my persistence.xml is okay because I can create the Session Factory manually:
EntityManagerFactory test = Persistence.createEntityManagerFactory("sbPersistenceUnit");
and all other injections are working fine. Does anybody know what might be missing?
In an unit-test you aren't in a managed environment.
OpenWebBeans would support it via the openwebbeans-resource module + #PersistenceUnit, but that isn't portable.
So you need to use e.g.:
#Specializes
public class TestEntityManagerProducer extends EntityManagerProducer {
private EntityManagerFactory emf = Persistence.createEntityManagerFactory("...");
#Produces
//...
#Override
protected EntityManager create() {
return emf.createEntityManager();
}
#Override
protected void close(#Disposes EntityManager em) {
if (em.isOpen()) {
em.close();
}
}
}
in the test-classpath
If you ask such questions on their mailing-list, you get answers petty quickly.
You will need to use #PersistenceUnit to inject EntityManagerFactory. #PersistentContext is used for EntityManager injection.
Do you define your entitymanagerFactory as a bean?
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
Currently, I'm using PersistenceContext to inject an EntityManager. The EM is injected perfectly.
#Stateless
public StatelessSessionBean implements StatelessSessionBeanLocal {
#PersistenceContext(unitName = "MyPersistenceUnit")
private EntityManager em;
#Override
public Collection<MyObject> getAllObjects(){
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriqQuery<MyObject> query = cb.createQuery(MyObject.class);
query.from(MyObject);
return em.createQuery(query).getResultList();
}
}
Now I try to decorate the bean, and suddenly the em doesn't get injected. I get a NullPointerException.
#Decorator
public StatelessSessionBeanDecorator implements StatelessSessionBeanLocal {
#Inject
#Delegate
#Any
StatelessSessionBeanLocal sb
#Override
public Collection<MyObject> getAllObjects(){
System.out.println("Decorated method!");
return sb.getAllObjects();
}
}
I know EJB and CDI are 2 completely different managers, so the one doesn't know about the other. I'm expecting that #PersistenceContext is an EJB injection point, while #Inject is a CDI one. What should I do to solve this and get the EntityManager to be injected like it should?
The best practice for persistence context and CDI is to make them CDI bean to avoid these kind of issue.
public class MyProducers {
#Produces
#PersistenceContext(unitName = "MyPersistenceUnit")
private EntityManager em;
}
After that you'll be able to inject the EntityManager in CDI way. Taking your EJB it'll be :
#Stateless
public StatelessSessionBean implements StatelessSessionBeanLocal {
#Inject
private EntityManager em;
#Override
public Collection<MyObject> getAllObjects(){
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriqQuery<MyObject> query = cb.createQuery(MyObject.class);
query.from(MyObject);
return em.createQuery(query).getResultList();
}
}
This way, you'll be able to decorate your CDI bean with no issue.
If you have multiple EntityManagers you can use CDI qualifiers to distinguish them
#PersistenceContext is an EJB injection point, while #Inject is a CDI one
Actually, no. #PersistenceContext annotation can be used in CDI and is not connected with EJB. You can do something like this:
#Named
public class EntityDAO {
#PersistenceContext
private EntityManager manager;
...
}
EJB uses #EJB annotation to inject other EJB, but it can inject any CDI bean or persistence context with same annotations.
I am currently trying to figure out the best way to get a entity manager and a usertransaction in my application.
In JBoss 5.1 I was able to inject it directly into the JSP file, but this is not permitted anymore:
<%!#PersistenceContext(unitName = "unitname")
public EntityManager em;
#Resource
UserTransaction utx;
%>
I have to access em and utx from different locations in my application such as Servlets and Controller classes. So it would be great to have it in one place and to access it globally, but I did not figure out yet how to do it. Any hint would be appreciated.
I found out how to get the EntityManager and the UserTransaction in Servlets, Controller Classes and JSP files.
Let's start with SessionBeans. I redefined all my controller classes as Stateless SessionBeans. Session Beans allow ressource injection. This is how I did it:
#Stateless
public class UserHandling {
#PersistenceContext(unitName = "SSIS2")
private static EntityManager em;
#Resource
private UserTransaction utx;
public User getUser(int userId) {
User userObject = em.find(User.class, userId);
return userObject;
}
}
If another Session Bean is needed in a Session Bean Class, it can be injected with the #EJB annotation:
#Stateless
public class UserHandling {
#PersistenceContext(unitName = "SSIS2")
private static EntityManager em;
#Resource
private UserTransaction utx;
#EJB
UserHandling uh; RoleHandling rh;
public User getUser(int userId) {
User userObject = em.find(User.class, userId);
return userObject;
}
}
In JSP files, you can get the Session Bean Controller classes by lookup the InitialContext:
<%
InitialContext ic = new InitialContext();
UserHandling uh = (UserHandling) ic.lookup("java:app/" + application.getContextPath() + "/UserHandling");
%>
The Issue being Solved
Servlets and JSPs must be stateless because they are shared across multiple threads. An EntityManager does keep state, and so a single instance cannot be shared by concurrent threads.
We'd like a smooth/seamless mechanism for obtaining an EntityManager, preferably managed by the Servlet container.
Servlet-Container Managed Persistence Context
Let's introduce a ContainerManagedPersistenceContext into the Servlet/JSP runtime.
We'll define it in a moment. Let's first look at how it can be used to inject an EntityManager into JSP:
<%! #Inject
#ContainerManagedPersistenceContext.Qualifier
public EntityManager em;
%>
or, better yet into a controller (because we do want to separate data recovery/business logic from our JSP, right?):
#Named
#SessionScoped
public class SessionController implements Serializable
{
...
#Inject
#ContainerManagedPersistenceContext.Qualifier
private EntityManager em;
}
But I don't (yet) have CDI available
If you don't have CDI, but you do have JSF, then the context can be injected as an old-style standard JSF #ManagedProperty:
#Named
#SessionScoped
public class SessionController implements Serializable
{
...
#ManagedProperty(value = "#{containerManagedPersistenceContext}")
ContainerManagedPersistenceContext cmpContext;
...
public void myMethod() {
EntityManager em = cmpContext.getEntityManager();
try {
...
} finally {
em.close();
}
}
}
Remember that - for all the same reasons that we have to go to this effort in the first place - the EntityManager must never be cached/preserved anywhere.
Transactions
Use the EntityTransaction provided by the EntityManager for begin/commit/rollback:
EntityTransaction transaction = em.getTransaction();
ContainerManagedPersistenceContext
This is defined as an application scoped controller and a PersistenceContext:
#PersistenceContext(name = ContainerManagedPersistenceContext.NAME,
unitName = ContainerManagedPersistenceContext.UNIT_NAME)
#ApplicationScoped
public class ContainerManagedPersistenceContext implements Serializable
{
private static final long serialVersionUID = 1L;
// UNITNAME must match persistence.xml: <persistence-unit name="myUnitName">
public static final String UNITNAME = "myUnitName";
public static final String NAME = "persistence/" + UNIT_NAME;
#Qualifier
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.METHOD, ElementType.FIELD,
ElementType.PARAMETER, ElementType.TYPE})
public static #interface Qualifier { }
// Servlets must be stateless (shared across multiple threads).
// EntityManager is not stateless (cannot be shared across threads).
// Obtain Container Managed EntityManager - and do NOT cache.
#Produces #Qualifier
public static EntityManager getEntityManager() throws NamingException
{
EntityManager lookup = InitialContext.doLookup("java:comp/env/" + NAME);
return lookup;
}
}
Limitations
As written, this defines a specifically named PersistenceContext for the Servlet container. Since the unitName isn't parameterized, it doesn't provide the level of flexibility as:
#PersistenceContext(unitName = "unitname")
public EntityManager em;
Alternatives
Define a PersistenceContext on your Servlet, and use JNDI name lookup.
Well i think you should see the problem from a different point of view?
Why do you need to call an EJB from JSP page?
JSP page shouldn't contain codes and it is used only for presentation.
I suggest to you to add a Servlet or a JSF framework and let the Servlet or the ManagedBean to call EJB and then pass the parameters to the JSP.
Hope it helps you
You can use the following snippet to retrieve EntityManager and/or UserTransaction via JNDI lookup:
try {
Context ic = (Context) new InitialContext();
EntityManager em = (EntityManager) ic.lookup("java:comp/env/*<persistence-context-name>*");
UserTransaction ut = (UserTransaction) ic.lookup("java:comp/env/UserTransaction");
} catch (NamingException ne) {...}
I am using JPA with Spring. If I were to let Spring handle the transactions, then this is what my Service layer would look like assuming the EntityManager has been properly injected into the DAOs:
MyService {
#Transactional
public void myMethod() {
myDaoA.doSomething();
myDaoB.doSomething();
}
}
However, if I were to do transactions manually, I have to make sure to pass that instance of EntityManager into each of the DAOs within a transaction. Any idea how can this be better refactored? I fee ugly doing new MyDaoA(em) or passing em into each DAO method like doSomething(em).
MyService {
private EntityManagerFactory emf;
public void myMethod() {
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
MyDaoA myDaoA = new MyDaoA(em);
MyDaoB myDaoB = new MyDaoB(em);
try {
tx.begin();
myDaoA.doSomething();
myDaoB.doSomething();
tx.commit();
} catch(Exception e) {
tx.rollback();
}
}
}
However, if I were to do transactions
manually, I have to make sure to pass
that instance of EntityManager into
each of the DAOs within a transaction.
This is where you are wrong. From the Spring Reference, JPA section:
The main problem with such a DAO is
that it always creates a new
EntityManager through the factory. You
can avoid this by requesting a
transactional EntityManager (also
called "shared EntityManager" because
it is a shared, thread-safe proxy for
the actual transactional
EntityManager) to be injected instead
of the factory:
public class ProductDaoImpl implements ProductDao {
#PersistenceContext
private EntityManager em;
public Collection loadProductsByCategory(String category) {
Query query = em.createQuery(
"from Product as p where p.category = :category");
query.setParameter("category", category);
return query.getResultList();
}
}
The #PersistenceContext annotation has
an optional attribute type, which
defaults to
PersistenceContextType.TRANSACTION.
This default is what you need to
receive a shared EntityManager proxy.
add this to your spring config
<bean p:entityManagerFactory-ref="emf" class='org.springframework.orm.jpa.support.SharedEntityManagerBean' />
now you can #Autowired EntityManager inside your dao
for the transaction management, since you already using spring, and #Transactional annotation, i assume you already have one transaction manager declared in your spring.xml
so using spring's transaction management
as
transactionStatus = platformTransactionManager.getTransaction(new DefaultTransactionDefinition());
// do your work here
platformTransactionManager.commit(transactionStatus );
Shot in the dark a bit I guess, but do you know you can do:
TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
That usually eliminates the majority of cases where you would want/need to use programmatic transactions in a system that otherwise has declarative transactions.