Glassfish 4 - TransactionRequiredException using Hibernate and CDI #Transactional - java

I am getting the following exception:
javax.el.ELException: javax.persistence.TransactionRequiredException
at com.sun.el.parser.AstValue.invoke(AstValue.java:279)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
Caused by: javax.persistence.TransactionRequiredException
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:161)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTransactionScopedTxCheck(EntityManagerWrapper.java:151)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:299)
I am using Hibernate 4.3.5
#Named
#SessionScoped
public class MenuBean implements Serializable {
#PersistenceContext
private EntityManager entityManager;
#Transactional
public void create() {
MenuTitle menu = new MenuTitle();
menu.setLabel(label);
entityManager.persist(menu); //exception in this line
label = null;
}
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://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="MyPersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>MySQL5</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.current_session_context_class" value="jta"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>
<property name="hibernate.hbm2ddl.auto" value="none"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
</properties>
</persistence-unit>
I have also tried to set hibernate.transaction.jta.platform to org.hibernate.engine.transaction.jta.platform.internal.SunOneJtaPlatform but it results in the same error.
EJB CMT´s are working fine.
The Create action is called from a commandButton:
<p:commandButton value="Create" process="#this type" update=":megaMenuForm:mainMenu" actionListener="#{menuBean.create()}" oncomplete="closeMenuDialog(xhr, status, args)"/>

See EJB specs if you want to manage transaction. Inject a resource UserTransaction.
Also #Transactional with not do anything here since you are using EJB.
In general you example should work, and #Transactional annotation will be just ignored. Could you try to make an interface, and call create method through it?
Looks like you are using EJB 2 style coding, but Glassfish 4 implements EJB 3.1, so it is better to go with a new one.

Related

JPA connect to Derby Database with Hibernate-ORM related problem in Quarkus

Currently, I am trying to build an API with JPA and Derby Database, and I've got some problems with Hibernate Reactive/Hibernate ORM.
Particularly, I want to connect to a Derby database server as follows:
QueryService.java:
#Transactional
#RequestScoped
public class QueryService implements Serializable {
#PersistenceContext
EntityManagerFactory emf;
private final static Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
public QueryService() {}
#PostConstruct
public void init() {
String urlDB = "my-persistence-unit";
emf = Persistence.createEntityManagerFactory(urlDB);
}
#PreDestroy
public void destroy() {
emf.close();
}
application.properties:
quarkus.hibernate-orm.database.generation=none
quarkus.datasource.db-kind=derby
quarkus.datasource.jdbc.url=jdbc:derby://localhost:1527/appDB;create=true
quarkus.datasource.jdbc.driver=org.apache.derby.jdbc.ClientDriver
quarkus.datasource.username=admin
quarkus.datasource.password=admin
quarkus.live-reload.instrumentation=true
In the persistence.xml file, I define a persistence unit to be used by the EntityManagerFactory in QueryService.java.
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
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_2.xsd">
<persistence-unit
name="my-persistence-unit"
transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/appDB;create=true"/>
<property name="hibernate.connection.username" value="admin"/>
<property name="hibernate.connection.password" value="admin"/>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
If I run this, I get this error: { "details": "Error id 07333181-bf2e-4640-8497-01de9bf6ccf7-1, java.lang.NullPointerException: Cannot invoke \"io.quarkus.hibernate.orm.runtime.recording.RecordedState.isReactive()\" because \"recordedState\" is null", "stack": "java.lang.NullPointerException: Cannot invoke \"io.quarkus.hibernate.orm.runtime.recording.RecordedState.isReactive()\" because \"recordedState\" is null\r\n\tat io.quarkus.hibernate.orm.runtime.FastBootHibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(FastBootHibernatePersistenceProvider.java:172)\r\n\tat io.quarkus.hibernate.orm.runtime.FastBootHibernatePersistenceProvider.createEntityManagerFactory(FastBootHibernatePersistenceProvider.java:66)\r\n\tat javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:80)\r\n\tat javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)\r\n\tat app.QueryService.init(QueryService.java:29)\r\n\tat app.QueryService_Bean.create(Unknown Source)\r\n\tat app.QueryService_Bean.create(Unknown Source)\r\n\tat io.quarkus.arc.impl.RequestContext.getIfActive(RequestContext.java:74)\r\n\tat io.quarkus.arc.impl.ClientProxies.getDelegate(ClientProxies.java:30)\r\n\tat app.QueryService_ClientProxy.arc$delegate(Unknown Source)\r\n\tat app.QueryService_ClientProxy.obtainCourseList(Unknown Source)\r\n\tat app.Scolarite.obtainCourseList(Scolarite.java:49)\r\n\tat app.Scolarite_Subclass.obtainCourseList$$superforward1(Unknown Source)\r\n\tat app.Scolarite_Subclass$$function$$2.apply(Unknown Source)\r\n\tat io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:133)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:104)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.doIntercept(TransactionalInterceptorRequired.java:38)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.intercept(TransactionalInterceptorBase.java:58)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.intercept(TransactionalInterceptorRequired.java:32)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired_Bean.intercept(Unknown Source)\r\n\tat io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:42)\r\n\tat io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)\r\n\tat io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:33)\r\n\tat app.Scolarite_Subclass.obtainCourseList(Unknown Source)\r\n\tat app.Scolarite_ClientProxy.obtainCourseList(Unknown Source)\r\n\tat app.ScolariteApplication.getCourseList(ScolariteApplication.java:22)\r\n\tat app.ScolariteApplication$quarkusrestinvoker$getCourseList_9c2e0d4fdac50820476d652c171e60223f72a1d5.invoke(Unknown Source)\r\n\tat org.jboss.resteasy.reactive.server.handlers.InvocationHandler.handle(InvocationHandler.java:29)\r\n\tat io.quarkus.resteasy.reactive.server.runtime.QuarkusResteasyReactiveRequestContext.invokeHandler(QuarkusResteasyReactiveRequestContext.java:114)\r\n\tat org.jboss.resteasy.reactive.common.core.AbstractResteasyReactiveContext.run(AbstractResteasyReactiveContext.java:145)\r\n\tat io.quarkus.vertx.core.runtime.VertxCoreRecorder$14.runWith(VertxCoreRecorder.java:576)\r\n\tat org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)\r\n\tat org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)\r\n\tat org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29)\r\n\tat org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29)\r\n\tat io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)\r\n\tat java.base/java.lang.Thread.run(Thread.java:833)" }
I tried to search for this on the internet, and it is said that this was because Hibernate Reactive and Hibernate Orm cannot be used together. But I don't know how to solve it. I am quite new to this. Could you please help me with it?

JBoss EAP 6.3 CMT Multiple persistence units

This is essentially a duplicate of How to locate the source of JBAS011470 error in JBoss?
But essentially, As soon as I add a second persistence unit, it gives me this error. It's ridiculous. I'm not going to disable the JPA subsystem like some people suggest - that sounds wrong.
My persistence.xml setup is as follows, where java:/NAME is set up as a datasource in standalone.xml:
<?xml version="1.0"?>
<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="name" transaction-type="JTA">
<jta-data-source>java:/NAME</jta-data-source>
<class>za.co.classes.A</class>
<class>za.co.classes.B</class>
<class>za.co.classes.C</class>
<properties>
<property name="hibernate.transaction.jta.platform"
value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/>
<property name="hibernate.transaction.manager_lookup_class"
value="org.hibernate.transaction.JBossTransactionManagerLookup"/>
<property name="jboss.entity.manager.factory.jndi.name"
value="java:jboss/persistence/NAME" />
<property name="jboss.entity.manager.jndi.name"
value="java:jboss/persistence/em/NAME" />
<property name="hibernate.dialect" value="za.co.equrahealth.dao.SQLServerDialect" />
</properties>
</persistence-unit>
The error starts as soon as I add a second persistence unit. So spring context is irrelevant.
Well, I luckily have multiple databases within the same schema, so I came up with a workaround. But it's obviously not going to solve the problem when there are multiple schemas. I think the cause of this issue might actually be a bug in JBoss.
#PersistenceContext
private EntityManager entityManager;
private EntityManager getEntityManager(String source)
{
if ("a".equalsIgnoreCase(source))
{
entityManager.createNativeQuery("USE A_DB;").executeUpdate();
}
else
{
entityManager.createNativeQuery("USE B_DB").executeUpdate();
}
return entityManager;
}

Vaadin JPAContainer doesn't work

I created a web app application like my work thesis. This application used the entire stack java EE 6: JPA2, EJB, JSF, RichFaces....
Now i'm trying to change the UI of my application from RichFaces to Vaadin. The first problems began with use of JPA container. i can't get a instance of entitymanager.
this is 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">
<jta-data-source>java:jboss/VaadinDS</jta-data-source>
<class>org.mypackage.entity.Utente</class>
<class>org.mypackage.entity.Indirizzo</class>
<class>org.mypackage.entity.Paese</class>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.show_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
this is my singelton class where i want to get the i instance of entitymanager
public class Utility {
private static EntityManager entityManager;
public Utility() {
// TODO Auto-generated constructor stub
}
public static EntityManager getInstance(){
if(entityManager == null)
entityManager = JPAContainerFactory.createEntityManagerForPersistenceUnit("primary");
return entityManager;
}
}
but doesn't work , i showed always the followed error:
[com.vaadin.server.DefaultErrorHandler] (http-localhost-127.0.0.1-8080-1) : java.lang.NullPointerException
where i wrong?
Your persistence.xml file needs to have a dialect property
Also, you need 2 other things that the book of vaadin explain if you are using hibernate with the jpacontainer: The use of one entity manager per reqeust pattern and the use of hibernate lazy loading delegate on your entity provider. If you need more help, I'll keep updating this answer.

How to update entity in JPA

This is my first real exposure to JPA and I'm trying to run the simplest of update statements. I'm running inside a jBoss 7.1.x server using Hibernate as JPA implementation. Any help would be greatly appreciated..
Here is my producer method for EntityManager:
#ApplicationScoped
public class EntityManagerProducer
{
#PersistenceContext
private EntityManager entityManager;
#Produces
#RequestScoped
public EntityManager getEntityManager()
{
return entityManager;
}
}
Here is the DAO method that tries to perform the update:
#Inject EntityManager em;
public void updateRequestStatus(String requestNumber, String newStatus)
{
em.getTransaction().begin();
ServiceRequestEntity serviceRequestToUpdate = em.find(RequestEntity.class, requestNumber);
requestToUpdate.setStatus(newStatus);
em.merge(serviceRequestToUpdate);
em.getTransaction().commit();
}
Here is 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_2_0.xsd"
version="2.0">
<persistence-unit name="database" transaction-type="RESOURCE_LOCAL">
<jta-data-source>java:/jdbc/myDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="false" />
<property name="hibernate.use_sql_comments" value="true" />
</properties>
</persistence-unit>
</persistence>
Here is the error message (can provide full stacktrace if needed -it chokes on the "merge" line):
javax.persistence.TransactionRequiredException: JBAS011469: Transaction is required to perform this operation (either use a transaction or extended persistence context)
....
at org.jboss.weld.proxies.EntityManager$-1727851269$Proxy$_$$_WeldClientProxy.merge(EntityManager$-1727851269$Proxy$_$$_WeldClientProxy.java) [weld-core-1.1.5.AS71.Final.jar:]
#Inject annotation on EntityManager I don't think will work. With your current setup I believe you want to inject your EntityManagerProducer class (which is not used in your DAO), and then call your getEntityManager method on it.
The other option would just be to use the #PersistenceContext in your DAO.
You also may want to specify the name of your persistence context as specified in your persistence.xml like:
#PersistenceContext(name="database")

An application using EJB 3.0 and Hibernate persistence provider gives an UnknownServiceException

I am trying to create a web app using JSF and EJB 3.0.
I am using plain JSF, Glassfish Server, Hibernate as my persistance provider. My database is apache derby.
Here my Stateless Session bean as follows:
#Stateless
#TransactionManagement(TransactionManagementType.CONTAINER)
public class StudentServiceBean implements StudentService{
#PersistenceContext(unitName="forPractise")
private EntityManager entityMgr;
#Resource
private SessionContext sessionContext;
#Override
public List<StudentVO> fetchStudentListOrderByStudentId(boolean flag){
List<StudentEntity> studentList = null;
TypedQuery<StudentEntity> studentQuery = null;
List<StudentVO> studentVOList = null;
String queryDesc = "select s from StudentEntity s order by s.studentId desc";
String query = "select s from StudentEntity s order by s.studentId";
try{
if(!flag){
studentQuery = entityMgr.createQuery(query,StudentEntity.class);
}else{
studentQuery = entityMgr.createQuery(queryDesc,StudentEntity.class);
}
studentList = studentQuery.getResultList();
studentVOList = new ArrayList<StudentVO>();
for(StudentEntity studentE : studentList){
studentVOList.add(new StudentVO(String.valueOf(studentE.getStudentId()),studentE.getStudentName(),studentE.getContactNumber()));
}
}catch(Exception e){
System.out.println(" EXCEPTION IN "+this.getClass().getName()+" in method fetchStudentListOrderByStudentId "+e);
}
return studentVOList;
}
And this is my 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_2_0.xsd"
version="2.0">
<persistence-unit name="forPractise" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/app</jta-data-source>
<class>com.entity.StudentEntity</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.SunONETransactionManagerLookup" />
</properties>
</persistence-unit>
</persistence>
What happens is on load of the JSP page, the getter method of StudentList is called -
inside the getter method I have written logic that if studentList is empty then call the studentService.fetchStudentListOrderByStudentId(true);.
But when I do this I get an exception:
EXCEPTION IN com.bb.StudentServiceBean in method
fetchStudentListOrderByStudentId
org.hibernate.service.UnknownServiceException: Unknown service
requested
[org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
Can you please tell me what I am missing, or where I am going wrong?
Thanks.
You indicate that you are using Hibernate 4.x, but the class you mentioned afaik is only valid for JPA 1.0 and Hibernate 3.x. Try removing the following line from your configuration:
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.SunONETransactionManagerLookup" />
Just in case it's of any interest, I got this error on Jetty when trying to start a Hibernate session:
Unknown service requested [org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
The root cause was a previous Exception (a few seconds earlier in the logs) which caused the spring context (WebAppContext) to fail to initialize.
Once I fixed the spring context, the "Unknown service requested" fixed itself. So, if you're seeing this error it's worth checking for earlier errors before investigating too much..

Categories

Resources