EntityManager not injected - java

I'm getting an NPE for my EntityManager and can't figure out why - can anyone spot my mistake?
UserManagerImpl.java
#Stateless
public class UserManagerImpl implements UserManager {
#PersistenceContext(unitName = "persistenceUnit")
EntityManager em;
public List<User> findUsers() {
return (List<User>) em.createQuery("from User").getResultList();
}
}
META-INF/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="persistenceUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/DefaultDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
</persistence-unit>
</persistence>
These are inside my ejb jar project, the UserManagerImpl is invoked from a JSP, not sure that should make a difference though.
Thanks in advance.

When you are using new UserManagerImpl() the container has no way to inject the EntityManager into this class. You need to let the container inject an instance into your object using
#EJB
private UserManager userManager;
This will only work for container managed objects like JSF managed beans, servlets or JSPs. Alternatively you can look up the ejb from jndi using something like
new InitialContext().lookup("UserManagerImpl");
The actual jndi name might be different.

Related

#PersistenceContext is null on Glassfish embedded (no ejb)

im facing following problem. In my application I'm trying to use #PersistenceContext injected into the NON ejb instance of DAO by Glassfish embedded server. So it's a pojo controlled by CDI. Like this :
#Named
public class DummyDAO implements Serializable {
#PersistenceContext private EntityManager entityManager;
public void testManager() {
if (entityManager == null) {
throw new RuntimeException("It's null!!");
}
System.out.println("Hello! I'm injected");
}
}
This dummy DAO injects into a JSF bean by CDI like this :
#ManagedBean
#SessionScoped
public class OrderImportManagerBean implements Serializable {
#Inject
DummyDAO dummyDAO;
public void testManager() {
dummyDAO.testManager();
}
}
testManager() called from an xhtml page like #{orderImportManagerBean.testManager}
entityManager is always null. The CDI itself works, all instances injected as they should but not this one. I have persistence.xml and orm.xml under resources/META-INF catalog. So after the project is packaged I get META-INF and stuff in right place (classes/META-INF). Here is my persistence.xml :
<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="persistance-unit" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:testdb"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.dialect"
value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name = "hibernate.show_sql" value = "true" />
</properties>
</persistence-unit>
</persistence>
Now I'm wondering what is wrong with my configuration? Any suggestions?
Thanks.

LazyInitializationException in SpringMVC frontend with EJB backend

I have an EJB application on JBoss AS 7.1.1, that use Hibernate 4.3 for database connection via jta-data-source. My persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
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">
<persistence-unit name="primary" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/postds</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.ProgressDialect" />
<property name="hibernate.connection.charSet" value="UTF-8" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
I use DAO pattern like this:
#Stateless
public abstract class GenericHibernateDAO<T, ID extends Serializable>
implements GenericDAO<T, ID> {
private Class<T> persistentClass;
#PersistenceContext
private EntityManager em;
protected Session getSession() {
return em.unwrap(Session.class);
}
public T save(T entity) {
getSession().saveOrUpdate(entity);
return entity;
}
...
In EJB backend all Lazy-initialized fields work fine. Now I need a small web admin panel for my backend. I am familiar with Spring MVC and decided use it. In Spring MVC is not a problem use EJB beans. But Lazy-initialized fields don't work in Spring controllers and I get:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
I tried to use OpenSessionInViewFilter in web.xml:
<filter>
<filter-name>openSessionFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionFilter</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
OpenSessionInViewFilter needs sessionFactory bean. I added it's definition into applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd">
<jee:jndi-lookup id="dataSource" jndi-name="java:/postds"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
But it did not solve my problem... Have you any advice?
Thanks a lot!
If you use EJB container manages transactions and sessions for you. After transaction commit (by default all EJB methods are transactional) container destroy the session. If you use lazy loading then you get the org.hibernate.LazyInitializationException.
Try use fetch join lazy loaded fields via HQL or Criteria API.
Please see this answer for more information.

#PersistenceUnit annotation not working

I want to use the #PersistenceUnit annotation in my app to create an application managed EntityManager
#PersistenceUnit(unitName="primary")
private static EntityManagerFactory entityManagerFactory;
EntityManager entityManager = entityManagerFactory.createEntityManager();
This doesn't seem to be working. I run my code through a debugger and discover that entityManagerFactory is null. My guess is that the injection of Persistence context with the #PersistenceUnit annotation is not working.
My app is a CDI app. It was not previously a CDI application - I converted it to CDI by creating a beans.xml file in WEB-INF, I needed to in order to do something like this.
Is there anything I need to configure within CDI to get the annotation to work? Thanks.
I have a JPA application running with only Java SE. I don't have a WEB-INF/beans.xml, but I do have a META-INF/persistence.xml configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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">
<persistence-unit name="JPAPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>jpa.Container</class>
<class>jpa.Item</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby:D:\NetBeansProjects\JPA\jpaTestDB;create=true"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
Container and Item are the two persistence classes in my jpa package.
This was generated automatically by Netbeans. There is also some information about using JPA without Java EE in the official (Sun/Oracle) Java EE tutorial in the persistence chapter.

How do injection with JPA?

Is possible do injection in EntityManager with EclipseLink 2.3 ?
This is my persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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">
<persistence-unit name="SuaParte" transaction-type="RESOURCE_LOCAL">
// classes..
<properties>
<property name="eclipselink.jdbc.batch-writing" value="JDBC"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/schema"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>
I'm new with JPA so I created this persistence.xml file at first just to test to see if it works, but now I would like to use #PersistenceContext to don't have to worry about manage the EntityMangerFactory and EntityManager.
I'm using Eclipse Indigo Java EE Web Developers with GlassFish v3.
UPDATE:
I follow #Andrei Bodnarescu approach and this tutorial too and everything is fine to get a connection with my database through GF3:
And i change my persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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">
<persistence-unit name="SuaParte" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/mysql</jta-data-source>
//classes..
</persistence-unit>
</persistence>
So i try to persist something in my database:
#Stateless
#LocalBean
public class DaoUser {
#PersistenceContext(unitName="SuaParte")
private EntityManager em;
public void persist(User user){
try{
em.persist(user);
}catch(Exception e){
e.printStackTrace();
}
}
}
And it returns a java.lang.NullPointerException in em.persist(user);.
What am I doing wrong ?
You have to change the transaction-type to JTA as follows -
<persistence-unit name="SuaParte" transaction-type="JTA">
And then you can use #PersistenceContext as follows if you want Glassfish to inject the EntityManager into your EJB -
#Stateless
#LocalBean
public class MyEjb {
#PersistenceContext("SuaParte")
private EntityManager suaParteEM;
}
You can do in Servlet and ManagedBean too.
Also, on your Glassfish server you can create JDBC Connection Pool and JDBC Resource, give it a JNDI name and use it to declare your EntityManager in the persistence.xml as follows -
<persistence-unit name="SuaParte" transaction-type="JTA">
<jta-data-source>JNDI_Name_Of_JDBC_Resource</jta-data-source>
You can create the JDBC Resources on from the Glassfish Admin-Console.
BheshG's answer is very good, here's just some small addendums.
i think that in order to activate CDI and thus have dependency injection you need to create an empty beans.xml file that you must place in the WEB-INF folder of your project
To create a data source in GF3 and expose it via JNDI like BheshG sais, you must to basically this:
resources->JDBC->JDBC Connection pools and make a connection pool
Create a datasource that will use the pool.
(I wanted to post images with examples for conenction pool and datasource, but I can't since I don't have reputation points. In order to not seem spammy and trolly, I'm just gonna say: email me if you want more details or an example project, as I'm working on a tutorial on exactly that right now)
Now you can use that datasource in the persistence.xml file to attach it to a persistence unit:
<persistence-unit name="emJTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/postgre_ds_jta</jta-data-source>
<mapping-file>META-INF/emp-mappings.xml</mapping-file>
<class>model.Employee</class>
<class>model.ProjectManager</class>
<class>model.Department</class>
<class>model.Project</class>
<class>model.Phone</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>

JPA Entity found in unit tests, not in EJB

I have a DAO that uses JPA with a non-JTA data source and RESOURCE_LOCAL transactions. All of my unit tests that exercise the DAO work perfectly (data is inserted and retrieved from the database).
When I deploy my EJB to my Weblogic 10.3.3 server, however, I get the following exception:
Caused by: java.lang.IllegalArgumentException: Unknown entity bean class: class com.foo.bar.CatalogEntity, please verify that this class has been marked with the #Entity annotation.
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.find(EntityManagerImpl.java:576)
My persistence.xml (in WEB-INF/classes/META-INF):
<?xml version="1.0" ?>
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="cmf-awe-service" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<non-jta-data-source>MyDataSource</non-jta-data-source>
<class>com.foo.bar.CatalogEntity</class>
<properties>
<property name="eclipselink.cache.shared.default" value="false"/>
<property name="eclipselink.query-results-cache" value="false"/>
<property name="eclipselink.target-server" value="WebLogic_10" />
<property name="eclipselink.logging.level" value="FINEST" />
</properties>
</persistence-unit>
</persistence>
I have confirmed that the CatalogEntity class is in the WEB-INF/classes directory. Any ideas about why this works in unit tests but not when deployed to the application server?
Brian, I had the same issue here... and I solved by adding a PreDestroy method on my bean that closes EntityManagerFactory:
#PreDestroy
public void close()
{
emf.close();
}
I hope this can help you! Please vote if it works...

Categories