javax.persistence.PersistenceException: No Persistence provider for EntityManager named avaliacaoneomind - jpa

I have a EJB project example that uses #PersistenceContext to conect to my database.
This works fine, but since my new project isn't a EJB, I have to think of another way to to this.
So I came up with something like this:
EntityManagerFactory entityFactory = Persistence.createEntityManagerFactory("avaliacaoneomind");
EntityManager em = entityFactory.createEntityManager();
But when I do this, I get this error:
javax.persistence.PersistenceException: No Persistence provider for EntityManager named avaliacaoneomind
I know my persistence.xml is correct AND in the right place because when I use #PersistenceContext(name="avaliacaoneomind") as a test, my tables are created automaticaly in my DB. If I remove the #PersistenceContext away from my code, the tables arent created.
How do I fix this error? I tried all links possible to find and none of them seems to fix my problem.
Bellow is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence>
<!--Nome do contexto que configura o Provedor de PersistĂȘncia -->
<persistence-unit name="avaliacaoneomind">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/avaliacaoneomind</jta-data-source>
<properties>
<property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="both" />
</properties>
</persistence-unit>
</persistence>

You can achieve the entityManager through JNDI lookup
Context initCtx = new InitialContext();
javax.persistence.EntityManager entityManager =
(javax.persistence.EntityManager)initCtx.lookup(
"java:comp/env/avaliacaoneomind"
);

Related

How do I get my project to use a container managed Enitymanager lifecycle rather an Application managed one?

I've been at this for a while - hoping to get some help. The first persistence.xml gives the output below it. The alternate persistence.xml crashes with: javax.persistence.PersistenceException: No Persistence provider for EntityManager named com.topcat_mavenproject1_jar_1.0-SNAPSHOTPU Please let me know if there's anything I can ad to make this clearer.
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
#Stateless
public class NewClass {
#PersistenceContext(unitName ="com.topcat_mavenproject1_jar_1.0-SNAPSHOTPU")
static EntityManager containerManagedEntityManager;
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(
"com.topcat_mavenproject1_jar_1.0-SNAPSHOTPU");
EntityManager applicationManagedEntityManager = emf.createEntityManager();
System.out.println("Container managed entityManager: "+containerManagedEntityManager);
System.out.println( "Application managed entityManager: " +applicationManagedEntityManager);
}
}
The output:
[EL Info]: 2016-08-16 01:51:13.395--ServerSession(33510911)--EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
[EL Info]: connection: 2016-08-16 01:51:13.535--ServerSession(33510911)--file:/Users/me/NetBeansProjects/mavenproject1/target/classes/_com.topcat_mavenproject1_jar_1.0-SNAPSHOTPU login successful
[EL Warning]: metamodel: 2016-08-16 01:51:13.552--The collection of metamodel types is empty. Model classes may not have been found during entity search for Java SE and some Java EE container managed persistence units. Please verify that your entity classes are referenced in persistence.xml using either <class> elements or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element
Container managed entityManager: null
Application managed entityManager: org.eclipse.persistence.internal.jpa.EntityManagerImpl#6f139fc9
My persistence.xml:
<?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="com.topcat_mavenproject1_jar_1.0-SNAPSHOTPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/nutrition_DB"/>
<property name="javax.persistence.jdbc.user" value="app"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="javax.persistence.jdbc.password" value="pass"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
Alternate persistence.xml:
<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="persistenceUnit" transaction-type="JTA">
<jta-data-source>jdbc/dataSource</jta-data-source>
<class>test.domain.TestEntity</class>
</persistence-unit>
</persistence>
In order to have a container-managed entity manager, your should use the Java Transaction API (JTA) instead of RESOURCE_LOCAL. The different between them are :
JTA means the persistence is managed by the application server
RESOURCE_LOCAL means the persistence is managed by yourself.
You can see more difference for Persistence unit as RESOURCE_LOCAL or JTA?
So in your case, I suggest you to do the following :
Make sure you're in a Java EE environment, e.g. Tomcat, WildFly and not a Java SE.
Modify your PU com.topcat_mavenproject1_jar_1.0-SNAPSHOTPU, set transaction-type="JTA"
Make sure that your JTA data source (DS) is configured in the server and activated
Describe this data source in your persistence XML in tag jta-data-source
Inject the EntityManager into you java class using PersistenceContext as you've done. Since the persistence is managed by the application server, do not use entity manager factory anymore except you know exactly what you're doing.
However, it seems that you're under the Java SE environment. In the case, there isn't any Java EE container (application server). And therefore, you cannot benefit the JTA configuration :( You must use RESOURCE_LOCAL mode and manage everything yourself.

Container-managed EntityManger is null on Injection

I'm nearly new to JavaEE (JRE7/JDK1.7.0) and startet my first (maven based) Project on Eclipse (Luna).
Applicationserver is JBoss EAP 6.2.0.GA (AS 7.3.0.Final-redhat-14) which I updated to JSF2.2 by adding jsf-api-2.2.7.jar and jsf-impl-2.2.7.jar and registering in module.xml - which works perfect, by the way.
The problem/question is, why can't I get the EntityManager from the container (AS) with Injection, with following code in my Project:
#Stateless
public class SCatRep {
#PersistenceContext
EntityManager em;
private ...
*In persistence.xml there is only one persistenceunit defined. So no further arguments are necessary ... in my opinion?!
On the other hand, when I try to get the EntityManager from container with a lookup, the EntityManager is present and everything works fine. I used this code (for testing):
#Stateless
#PersistenceContext(unitName="scha", name="persistence/em")
public class SCatRep {
EntityManager em;
public SCatRep() {
try {
Context ic = new InitialContext();
em = (EntityManager) ic.lookup("java:comp/env/persistence/em");
} catch (NamingException e) {
e.printStackTrace();
}
}
I read a lot forums and tutorials - because this behaviour is discussed a lot - but can't get a solution or answer. Hope somebody can help me and point me to the right direction.
Thanks in advance.
EDIT:
I'm using EJB 3.1. And here is the 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="scha" transaction-type="JTA">
<jta-data-source>java:/scha_jndi</jta-data-source>
<properties>
<!-- SQL dialect -->
<property name="dialect" value="org.hibernate.dialect.MySQLDialect" />
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class" value="thread" />
<!-- Echo all executed SQL to stdout -->
<property name="show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
Thanks for help.
I tried to access the EntityManager in constructor ... which is not possible, due to the initializationprocess.
Now I put the Initial loading (databaseaccess) in a #PostConstruct-annotated method and this works perfectly.

Configuring EJB on JBoss AS 7 using JTA datasources: every statement is commited

everybody!
I've been trying to find the answer for some time but I didn't manage.
I try to configure my application and make it work under JBoss Application Server 7.1.1, using Enterprise Java Beans. My application is Web application, it uses servlets and injects other classes as EJBs. The problem is that every statement gets commited, so that means no transaction management is supported.
In my test example I have an entity with a collection of children (mapped with a relationship OneToMany with a property CascadeType.ALL). If a record in a collection has some problems (e.g. non-existing foreign key), it can't be inserted into table and throws exception. However, the parent entity gets inserted, so I assume the inserts are done in different separate transactions. This is strictly undesired behavior and I try to resolve it.
Technical parameters:
DBMS: Oracle EE 11g
AS: JBoss AS 7.1.1
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/">
<persistence-unit name="OracleEntityManager">
<jta-data-source>java:jboss/CmaDevDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9iDialect" />
<property name="hibernate.hbm2ddl.auto" value="none" />
<property name="hibernate.jdbc.batch_size" value="20" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.use_sql_comments" value="true" />
</properties>
</persistence-unit>
</persistence>
my EJB:
#Stateless(name="EntityWriter")
#TransactionManagement(TransactionManagementType.CONTAINER)
public class EntityWriter {
#Resource
private SessionContext context;
/*#Resource
UserTransaction ut;*/
#PersistenceContext(unitName = "OracleEntityManager",type=PersistenceContextType.EXTENDED)
EntityManager em;
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public EntityMarker insertEntity(EntityMarker entity)throws Exception
{
try
{
entity = em.merge(entity);
em.flush();
return entity;
}
catch (Exception e)
{
context.setRollbackOnly();
e.printStackTrace();
return null;
}
}
}
Actually I tried both EJB approaches: Container Management Transaction and Bean Management Transaction and neither works as I expect.
When I inject the bean into servlets I do it like this:
#EJB(name = "EntityWriter")
private EntityWriter entityWriter;
Now I think the bean is fine, probably something is missing in persistence.xml.
Would be grateful to any ideas. Thanks in advance!
Everything works correct after I edited Datasource configuration via JBoss Administration console and set a checkbox "Use JTA". It was unchecked by default.
You're right, Chris. Thanks!

How to use 2 PersistenceUnits in one Persistence.xml in a JavaEE application?

I am trying to access 2 different tables in my database.
Initially my persistence.xml was as follows:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="Persistence">
<jta-data-source>jdbc/classicmodels</jta-data-source>
<class>com.tugay.maythirty.model.Customers</class>
<class>com.tugay.maythirty.model.Products</class>
<class>com.tugay.maythirty.model.Employee</class>
<class>com.tugay.maythirty.model.Office</class>
</persistence-unit>
</persistence>
So I defined a DataSource in Glassfish following this great artical and my application was working fine. I was using #PersistenceContext annotation in my DAO classes with name="Persistence"
This basically is connected to a table called "classicmodels".
Then I needed to fetch some data from a table called "sakila". I added these lines to my persistence.xml:
<persistence-unit name="sakila">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.tugay.maythirty.model.Actor</class>
<class>com.tugay.maythirty.model.Film</class>
<class>com.tugay.maythirty.model.FilmActor</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/sakila"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="password"/>
</properties>
</persistence-unit>
And I have used this code in my DAO:
public List<Actor> getAllActors(){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("sakila");
EntityManager em = emf.createEntityManager();
TypedQuery<Actor> actorTypedQuery = em.createQuery("Select a from Actor a",Actor.class);
return actorTypedQuery.getResultList();
}
When I deploy my application to GlassFish however I started getting this Exception:
java.lang.RuntimeException: Could not resolve a persistence unit corresponding to the persistence-context-ref-name [Persistence] in the scope of the module called [may-thrity]. Please verify your application.
So it seems that now my Persistence Unit with name "Persistence" is gone.
What is it that I am doing wrong?
Have you tried explicitly declaring your persistence unit with
#PersistenceContext(unitName="Persistence")
instead of
#PersistenceContext(name="Persistence")
PersistenceContext doc

Cannot inject RESOURCE_LOCAL container managed EntityManager using #PersistenceContext

I am using JBoss AS 7.1.1 and able to configure a new JTA datasource and wire it to my EJB using
#PersistenceContext(unitName="TestPU")
private EntityManager entityManager;
When I tried to use RESOURCE_LOCAL PersistenceUnit I am getting the error saying I can't inject RESOURCE_LOCAL PU using #PersistenceContext.
I have configured my persistence.xml as follows:
<persistence-unit name="TestPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/xy"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="blah"/>
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
And in my DAO,
#Stateless
public class UserDAO {
#PersistenceContext(unitName="TestPU")
private EntityManager entityManager;
}
When I deployed my app on AS 7.1.1 I am getting the following error.
JBAS011428: Cannot inject RESOURCE_LOCAL container managed EntityManagers using #PersistenceContext
at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor$1.handle(ModuleJndiBindingProcessor.java:169)
at org.jboss.as.ee.component.ClassDescriptionTraversal.run(ClassDescriptionTraversal.java:54)
at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor.processClassConfigurations(ModuleJndiBindingProcessor.java:162)
at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor.deploy(ModuleJndiBindingProcessor.java:155)
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
... 5 more
Any solution to use RESOURCE_LOCAL PU with #PersistenceContext?
JTA : In Java EE environment, transactions are managed by the container & by default its JTA transaction. You can get entity manager by lookup or injection.
RESOURCE_LOCAL : In Java SE, application have to manage transactions explicitly & resource local transactions are native transactions. You have to create EntityManagerFactory & then can create entity manager from it.
As you are deploying it in application server, change the transaction-type to JTA in persistence.xml.