How to inject #PersistenceContext into pojo class - java-ee-6

I'm trying to inject PersistenceContex into POJO using #PersistenceContex annotation, I've read that i need to made that POJO managed to do that. So I inject my POJO class into servlet(so its now managed as dependent object, am i right ?) but when servlet is trying to call metod from injected object i get error:
java.lang.IllegalStateException:
Unable to retrieve
EntityManagerFactory for unitName null
So it looks like PersistenceContext is not injected into POJO properly, what should I do to make it work ?
My POJO class looks like this:
public class FileEntityControlerImpl implements FileEntityInterface {
#PersistenceContext
EntityManager entityManager;
#Override
public void createFile(FileEntity fileEntity) {
...}
#Override
public FileEntity retriveFile(String fileName) {
...}
Injection point:
#Inject
FileEntityInterface fileController;
If I use SLSB and inject using #EJB it works fine.
..::UPDATE::..
stacktrace:
WARNING: StandardWrapperValve[ResourcesServlet]: PWC1406: Servlet.service() for servlet ResourcesServlet threw exception
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName MambaPU
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.init(EntityManagerWrapper.java:121)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:162)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createNamedQuery(EntityManagerWrapper.java:554)
at pl.zawi.mamba.core.integration.controllers.implementation.FileEntityControlerImpl.retriveFile(FileEntityControlerImpl.java:32)
at pl.zawi.mamba.core.face.servlets.ResourcesServlet.doGet(ResourcesServlet.java:60)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at java.lang.Thread.run(Thread.java:662)
persistance.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="MambaPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/MambaDB</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<shared-cache-mode>ALL</shared-cache-mode>
<properties>
<!-- <property name="javax.persistence.jdbc.password" value="root"/>-->
<!-- <property name="javax.persistence.jdbc.user" value="root"/>-->
<!-- <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>-->
<!-- <property name="eclipselink.ddl-generation" value="create-tables"/>-->
<!-- <property name="eclipselink.logging.logger" value="org.eclipse.persistence.logging.DefaultSessionLog"/>-->
<property name="eclipselink.logging.level" value="ALL"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>
..::UPDATE2::..
If someone is interested there is sorce of my project, I've been using maven so it should be simple to build and run.(MySql drive is not included in pom-s so keep it in mind )
Mamba.Core

Just for the reference:
You don't use the #PersistenceContext annotation at all on Entity classes. Simply including a Persistence Unit with the POJOs will make them managed (adding a persistence.xml and an empty beans.xml into the META-INF folder of the JAR of the POJO classes.
#PersistenceContext is used on Session Beans and its purpose is to automatically inject the EntityManager into the session bean.

first, your pojo needs to be in a bean archive (have beans.xml in META-INF or WEB-INF) in order to be managed
#PersistenceContext requires a META-INF/persistence.xml, where you define a persistent unit
if there is a persistent unit and it still fails, try #PersistenceContext(unitName="name")

I have the same issue: Glassfish doesn't bring up EntityManager if DAO is not Stateless
I think that is a Glassfish issue, because works fine under JBoss AS 6.

I have the same issue. My SLSB injects my DAO ojbect with #Inject. The #PersistenceContext is in the POJO. When the POJO is in the same maven project as the EJB, everything works fine. Im not sure why, but the EJB cannot inject the POJO (w/ PU) when it is in a different project, unless I make the POJO a SLSB and use #EJB instead of #Inject.

Related

Unrecognized JPA persistence.xml XSD version : `` - hibernate, java ee and postgresql

The issue is appearing when trying to make entityManager with entitiManagerFactory.
Application is running inside docker container and postgresql database is on localhost of the machine (not inside docker).
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_1.xsd"
version="2.1">
<!-- Define persistence unit -->
<persistence-unit name="mypersistenceunit">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>some.path.SimplifiedUserGroup</class>
<class>some.path.UserSettings</class>
<class>some.path.UserGroupSettings</class>
<class>some.path.UserGroup</class>
<class>some.path.AppUser</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/localdatabase" />
<property name="javax.persistence.jdbc.user" value="postgres" />
<property name="javax.persistence.jdbc.password" value="postgres" />
</properties>
</persistence-unit>
and the repository class:
public List<SimplifiedUserGroup> findAll() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("mypersistenceunit");
entityManager = emf.createEntityManager();
return entityManager.createNamedQuery("UserGroup.findAll", SimplifiedUserGroup.class).getResultList();
}
there is an error:
javax.persistence.PersistenceException: Unable to locate persistence units
and then:
java.lang.IllegalArgumentException: Unrecognized JPA persistence.xml XSD version : ``
I tried several tutorials and read stackoverflow topics but nothing helps me - I tried with but didn't help. The same with versions 2.0, 2.1, 2.2.
I have such dependencies in my pom.xml:
dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.3.6.Final</version>
</dependency>
It would be great if I could create an entityManager and then connect to database (on localhost) and perform some queries...
Thanks!
PersistenceException :
If you use the EntityManagerFactory in a JavaEE environment you need to define the transaction-type to RESOURCE_LOCAL in your persistence.xml :
<persistence-unit name="mypersistenceunit" transaction-type="RESOURCE_LOCAL">
For more informations about the EntityManager and difference beetween transaction-type JTA and RESOURCE_LOCAL in the persistence.xml see this answer.
Unrecognized JPA persistence.xml XSD version :
In your persistence.xml :
I dont see the persistence enclosing tag </persistence> after </persistence-unit> at the end.
You are using an old URL for the XSD Schema Location, change your <persistence ... > to :
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
Informations from Oracle :
Starting with the 2.1 version, the Java Persistence API Schemas share the namespace, http://xmlns.jcp.org/xml/ns/persistence/. Previous versions used the namespace http://java.sun.com/xml/ns/persistence/.

No Persistence provider for EntityManager named test

I'm trying to develop a Java EE web application using JPA to manage the DB.
When I try to retrieve the rows from my database I've an error :
"No Persistence provider for EntityManager named test"
The code of my function using JPA is :
EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
EntityManager em =emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
#SuppressWarnings("unchecked")
List<InputHStock> iph = em.createQuery("from Student").getResultList();
for (Iterator<InputHStock> iterator = iph.iterator(); iterator.hasNext();) {
InputHStock student = (InputHStock) iterator.next();
System.out.println(student.getLocationCode());
}
tx.commit();
} catch (Exception e) {
tx.rollback();
}
}
My persistence.xml file :
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="test">
<class>application.InputHStock</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="javax.persistence.jdbc.user" value="testSQL" />
<property name="javax.persistence.jdbc.password" value="testpwd1" />
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
</properties>
</persistence-unit>
</persistence>
Here is my arborescence in eclipse :
I've also tried using the Eclipse tool to include JPA but without success.
Note that the connection to the database is working as I can retrieve my data when using directly JDBC.
Your persistence.xml is lacking a persistence provider. As you use EclipseLink, add
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
inside of the persistence-unit tag.
I think "hibernate-entitymanager" dependency missing in your pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.3.6.Final</version>
</dependency>
Probably you are using hibernate-core in pom. Use hibernate-entitymanager instead of hibernate-core for JPA.
Also requires provider tag in persistence.xml.
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
I was dealing with this error in a somewhat misleading scenario. Hibernate dependency was correctly added, persistence.xml was fine.
Turns out I hadn't included the database driver dependency on Maven.
I thought it wouldn't be relevant to my test, since I was not going to hit a DB. Just wanted to test the Query API.

Persistence error in JPA

I am creating a small JPA project.
But I am receiving the below error, when I run the main class.
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named ClientAccount
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:56)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:34)
at com.infinite.ClientAccountMain.main(ClientAccountMain.java:12)
the name in the persistence unit is the same used in the entity manager factory
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ClientAccount");
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="ClientAccount">
<description>My Persistence Unit</description>
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.infinite.Order</class>
<class>com.infinite.Account</class>
<class>com.infinite.Client</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://localhost:3306;databaseName=testdatabase" />
<property name="javax.persistence.jdbc.user" value="test"/>
<property name="javax.persistence.jdbc.password" value="test"/>
</properties>
</persistence-unit>
I think that Neil Stockton is right and if you search a bit you will find your answer. Although I think that must be something in relation with your provider information.
Try to put something like this.
For OpenJPA
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
Source information ---> http://openjpa.apache.org/builds/1.0.3/apache-openjpa-
1.0.3/docs/manual/jpa_overview_persistence.html
For Hibernate
<provider>org.hibernate.ejb.HibernatePersistence</provider>
There are multiple causes for this error:
You do not have the specified JPA provider on your classpath (check the JARs).
You did not define the persistence unit in your persistence.xml file.
Your persistence provider did not find your persistence.xml file (usually it is in META-INF/persistence.xml). Check that it is on the right place.

JPA: configure persistence provider

I got a simple java project created with maven (quickstart archetype)
I am trying to configure JPA persistence for drools sessions (the code comes from drools documentation)
I added drools-persistence-jpa, Bitronix Transaction Manager and com.h2database dependencies to my pom.xml
I created a META-INF folder as Source-Folder in my Eclipse Project in "src/META-INF"
I added the persistence.xml and jndi.properties file there.
In my TestCase I have following code:
[...]
EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.drools.persistence.jpa");
[...]
When running the test, I get the following Exception:
javax.persistence.PersistenceException: No Persistence provider for
EntityManager named org.drools.persistence.jpa at
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:69)
at
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at com.sample.MyTest.testJPA(MyTest.java:112)
I am relatively sure, that there's just something wrong with the way I created the META-INF or persistence.xml (see below). Any suggestions?
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:orm="http://java.sun.com/xml/ns/persistence/orm"
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
http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd">
<persistence-unit name="org.drools.persistence.jpa" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/testDatasource</jta-data-source>
<class>org.drools.persistence.info.SessionInfo</class>
<class>org.drools.persistence.processinstance.ProcessInstanceInfo</class>
<class>org.drools.persistence.processinstance.ProcessInstanceEventInfo</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.max_fetch_depth" value="3" />
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.connection.autocommit" value="true" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.BTMTransactionManagerLookup" />
</properties>
</persistence-unit>
</persistence>
I think the problem is related to the place where you put your persistence.xml file. Instead of src/META-INF you must place is either in src/main/resources/META-INF or src/test/resources/META-INF
Edited:
In your persistence.xml file you are stating that you want to use org.hibernate.ejb.HibernatePersistence as a provider. According to your comments, you are not including hibernate-entitymanager as a dependency [source]. Try to add that dependency.
Hope it helps,

what's wrong with my #PersistenceContext?

I'm using Eclipse Juno, Glassfish 3.1.2, and MySQL 5.1.
I'm building a simple EJB & JSF application. I created the following eclipse projects:
appEAR <-- the EAR file
appEJB <-- contains UserService.java EJB
appJPA <-- contains UserDAO.java EJB, and User.java object
appWeb <-- contains index.jsp
It's just a skeleton right now, but I can deploy the app and see the index.jsp
Next, I tried to add the following to the UserDAO ...
#PersistenceContext
EntityManager em;
But then when the app tries to republish, it gives me the error:
'Publishing to GlassFish 3.1.2 at localhost...' has encountered a problem. cannot Deploy appEar
There are no other details.
When I remove the two lines of #PersistenceContent code, the app deploys again.
Also, the persistence.xml file n the appJPA project is as follows:
<?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="appJPA">
<class>app.model.User</class>
</persistence-unit>
</persistence>
Please help ... what am I missing? I'm rather stuck.
Your persistence.xml is incomplete , you need to provide Connection properties to specify the provider ,which DB to connect etc
Heres an example using hibernate as the JPA provided
<persistence-unit name="educationPU"
transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.coe.jpa.StudentProfile</class>
<properties>
<property name="hibernate.connection.driver_class"
value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/COE" />
<property name="hibernate.connection.username" value="root" />
<property name="show_sql" value="true" />
<property name="dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
and heres a more Generic one
I am very new to glassfish, JPA and so on and I have really problems with setting that up. What I am planning to do is a simple RESTful service with a persistent backend. I am using glassfish3 as application server and already deployed a simple REST service with the jersey-library. Now I want to provide access to a database via JPA. Glassfish is shipped with JavaDB/derby and EclipseLink, is that right? So, I want to use that :-)
I created a persistence.xml in META-INF:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="myPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDataSource" /> <!-- org.apache.derby.jdbc.EmbeddedDriver -->
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/sample;create=true" />
<property name="javax.persistence.jdbc.user" value="APP" />
<property name="javax.persistence.jdbc.password" value="APP" />
<property name="eclipselink.ddl-generation" value="create-tables" />
</properties>
</persistence-unit>
</persistence>
I don't use glassfish. But I think the reason is that you didn't specify any datasource in the persistence.xml. you should do this in it, which you can use jndi or other way. and second, you should define the entityManagerFactory bean in spring context xml file.
Did you add the datasource in glasfish ? You will need to add the mysql jdbc drivers too. In Java EE, it's the persistence container (inside the server) which will create and manage the datasource for you.
See http://www.albeesonline.com/blog/2008/08/06/creating-and-configuring-a-mysql-datasource-in-glassfish-application-server/