Cannot inject RESOURCE_LOCAL container managed EntityManager using #PersistenceContext - jpa

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.

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.

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

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"
);

ServiceMix / Blueprint / JPA Integration

I have been spending the week attempting to integrate JPA / ServiceMix 4.5.1 / camel-jpa 2.10.4 / Blueprint together. I'm currently using OpenJPA, but am not tied to it. The version of aries jpa used by servicemix is 0.3.0.
The stack trace I cannot get past is:
org.osgi.service.blueprint.container.ComponentDefinitionException: Error when instanciating bean workoutEntity of class class [...].WorkoutEntity
at org.apache.aries.blueprint.container.BeanRecipe.getInstance(BeanRecipe.java:271)[10:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BeanRecipe.internalCreate(BeanRecipe.java:708)[10:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.di.AbstractRecipe.create(AbstractRecipe.java:64)[10:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.di.RefRecipe.internalCreate(RefRecipe.java:60)[10:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.di.AbstractRecipe.create(AbstractRecipe.java:64)[10:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BlueprintRepository.createInstances(BlueprintRepository.java:219)[10:org.apache.aries.blueprint:0.3.2]
[...]
Caused by: <openjpa-2.2.0-r422266:1244990 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: [javax.sql.DataSource]
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:218)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:156)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:227)
[...]
Caused by: java.lang.IllegalArgumentException: [javax.sql.DataSource]
at org.apache.aries.jndi.services.ServiceHelper.proxyPriviledged(ServiceHelper.java:348)
at org.apache.aries.jndi.services.ServiceHelper.access$700(ServiceHelper.java:65)
at org.apache.aries.jndi.services.ServiceHelper$1.run(ServiceHelper.java:285)
at java.security.AccessController.doPrivileged(Native Method)[:1.6.0_43]
[...]
I've attempted several variations. Here is my current configuration:
persistence.xml:
<persistence-unit name="customer1" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/prototypedb)</jta-data-source>
<class>...</class>
</persistence-unit>
camel-context.xml
<service id="PrototypeDB" interface="javax.sql.DataSource">
<service-properties>
<entry key="osgi.jndi.service.name" value="jdbc/prototypedb"/>
</service-properties>
<bean class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/prototype"/>
<property name="username" value="root"/>
<property name="password" value="..."/>
</bean>
</service>
<service ref="workoutEntity" interface="..."/>
<bean id="workoutEntity" class="...">
<jpa:unit index="0" unitname="customer1" />
<tx:transaction method="*" value="Required"/>
</bean>
Entity Bean (written in groovy)
#Entity
#Table(name='customer1')
#Slf4j
class WorkoutEntity implements IWorkoutEntity{
private EntityManager entityManager
WorkoutEntity(final EntityManagerFactory entityManagerFactory) {
this.entityManager = entityManagerFactory.createEntityManager()
}
#Handler
void create( #Body final String input) {
// ...
}
}
I've attempted multiple different implementations of a DataSource, including the BasicDataSource, org.springframework.jdbc.datasource.SimpleDriverDataSource, and com.mysql.jdbc.jdbc2.optional.MysqlDataSource. All cause the IllegalArgumentException.
I've also attempted to forego using JNDI and instead define the data source directly in the persistence.xml. This causes ClassNotFoundException in the OpenJPA bundle, as it is not importing the mysql driver. I'd prefer to define this in my camel-context.xml and would prefer to not re-bundle the OpenJPA jar.
You probably also need the aries JNDI features installed. This helps to call OSGi services via JNDI lookups. This should be the missing piece.

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