javax.ejb.EJBException java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName - java-ee-6

I'm working on a JavaEE application with EJB.
I have an Entity called Medico which code is:
#Entity
public class Medico implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
public Medico(String nome_medico, String morada_medico,
String esp, GregorianCalendar dnasc_medico, int tel_medico) { //construtor parametrico
super();
this.nome_medico = nome_medico;
this.morada_medico = morada_medico;
this.esp = esp;
this.dnasc_medico = dnasc_medico;
this.tel_medico = tel_medico;
}
#Id
#GeneratedValue
private int cod_medico; //bi
private String nome_medico;
private String morada_medico;
private String esp;
#Temporal(TemporalType.DATE)
private GregorianCalendar dnasc_medico;
private int tel_medico;
private ArrayList<GregorianCalendar> agenda_consultas;
private ArrayList<GregorianCalendar> agenda_atos;
private int total_atos;
private int total_presc;
public int getTotal_presc() {
return total_presc;
}
public void setTotal_presc(int total_presc) {
this.total_presc = total_presc;
}
public Medico(){ //construtor vazio
super();
}
public int getTotal_atos() {
return total_atos;
}
public void setTotal_atos(int total_atos) {
this.total_atos = total_atos;
}
public ArrayList<GregorianCalendar> getAgenda_consultas() {
return agenda_consultas;
}
public void setAgenda_consultas(ArrayList<GregorianCalendar> agenda_consultas) {
this.agenda_consultas = agenda_consultas;
}
public ArrayList<GregorianCalendar> getAgenda_atos() {
return agenda_atos;
}
public void setAgenda_atos(ArrayList<GregorianCalendar> agenda_atos) {
this.agenda_atos = agenda_atos;
}
public int getCod_medico() {
return cod_medico;
}
public void setCod_medico(int cod_medico) {
this.cod_medico = cod_medico;
}
public String getNome_medico() {
return nome_medico;
}
public void setNome_medico(String nome_medico) {
this.nome_medico = nome_medico;
}
public String getMorada_medico() {
return morada_medico;
}
public void setMorada_medico(String morada_medico) {
this.morada_medico = morada_medico;
}
public String getEsp() {
return esp;
}
public void setEsp(String esp) {
this.esp = esp;
}
public GregorianCalendar getDnasc_medico() {
return dnasc_medico;
}
public void setDnasc_medico(GregorianCalendar dnasc_medico) {
this.dnasc_medico = dnasc_medico;
}
public int getTel_medico() {
return tel_medico;
}
public void setTel_medico(int tel_medico) {
this.tel_medico = tel_medico;
}
#Override
public String toString() {
return "Medico [cod_medico=" + cod_medico + ", nome_medico="
+ nome_medico + ", morada_medico=" + morada_medico + ", esp="
+ esp + ", dnasc_medico=" + dnasc_medico + ", tel_medico="
+ tel_medico + "]";
}
}
Then I created a session bean implementation class:
#Stateless
public class HospitalManagement implements AdministradorSessionRemote,GestorSessionRemote {
/**
* Default constructor.
*/
#PersistenceContext(unitName="Hospital")
private EntityManager em;
public HospitalManagement() {
// TODO Auto-generated constructor stub
}
#Override
public String cria_medico(String nome_medico, String morada_medico,
String esp, GregorianCalendar dnasc_medico, int tel_medico) {
Medico md = new Medico (nome_medico, morada_medico, esp, dnasc_medico,tel_medico);
em.persist(md);
return "Medico "+Integer.toString(md.getCod_medico())+" criado!";
}
This class implements two interfaces, but the method above is only used in the following one:
#Remote
public interface GestorSessionRemote {
public String cria_medico(String nome_medico,String morada_medico,String esp,GregorianCalendar dnasc_medico, int tel_medico);
public String procura_nome_medico(String nome);
public String procura_cod_medico(int cod);
public String altera_morada_med(int cod, String morada);
public String altera_telemovel_med(int cod, int tel);
Then I created a client:
public class GestorClient {
public static void main(String[] args){
InitialContext ctx =new InitialContext();
GestorSessionRemote g=(GestorSessionRemote)ctx.lookup("java:global/HospitalEAR/Hospital/HospitalManagement!Sessions.GestorSessionRemote");
System.out.println(g.cria_medico(nomem, moradam, esp,cal,telm));
where the parameters of the method are obtained by scannig from the keyboard.
I've also created the following 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="Hospital">
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
When I try to deploy the application, an error occurs. Here is the complete stacktrace:
Exception in thread "main" javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBObjectInvocationHandlerDelegate.invoke(EJBObjectInvocationHandlerDelegate.java:79)
at com.sun.proxy.$Proxy236.cria_medico(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie.dispatchToMethod(ReflectiveTie.java:143)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:173)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName Hospital
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.init(EntityManagerWrapper.java:138)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:158)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTransactionScopedTxCheck(EntityManagerWrapper.java:151)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:281)
at Sessions.HospitalManagement.cria_medico(HospitalManagement.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:55)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:205)
... 19 more
Could someone help me understand the reason why this is happening?

The obvious problem is that you didn't specify a jta-data-source and the transaction-type in your persistence.xml.
A jta-data-source is specified like this:
<persistence-unit name="Hospital">
<jta-data-source>jdbc/sample</jta-data-source>
</persistence-unit>
You have to create the JDBC resource in your Glassfish instance. To do this open the Glassfish Admin GUI under http://localhost:4848 and create a Connection Pool under Resources -> JDBC Connection Pools. Then create a JDBC resource under Resources -> JDBC Resources named jdbc/sample and make it reference the new connection pool.
Further, it looks like the server somehow thinks that you want to use transaction-type RESOURCE_LOCAL which requires that you specify an EntityManagerFactory to get an instance of the EntityManager.
JTA should be the default transaction-type in a Java EE environment but you may have to explicitly specifiy the transaction-type in the persistence.xml like this:
<persistence-unit name="Hospital" transaction-type="JTA">
See also:
persistence.xml different transaction-type attributes

Related

Error: detached entity passed to persist | method save new is not persisting in the DB | Quarkus | GraphQL | Postgres | Hibernate

I managed to implement the CRUD functions. All are working fine except the addNew (save method).
when I execute that add method; I always get the error: "detached entity passed to persist ....."
bellow the error log:
__ ____ __ _____ ___ __ ____ ______
--/ __ \/ / / / _ | / _ \/ //_/ / / / __/
-/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\ \
--\___\_\____/_/ |_/_/|_/_/|_|\____/___/
2022-04-20 18:37:57,754 INFO [org.fly.cor.int.lic.VersionPrinter] (Quarkus Main Thread) Flyway Community Edition 8.4.2 by Redgate
2022-04-20 18:37:57,757 INFO [org.fly.cor.int.dat.bas.BaseDatabaseType] (Quarkus Main Thread) Database: jdbc:postgresql://localhost:5432/db-mcs-thirdparty (PostgreSQL 14.2)
2022-04-20 18:37:57,824 INFO [org.fly.cor.int.com.DbMigrate] (Quarkus Main Thread) Current version of schema "public": 1====--> 90% EXECUTING [13s]
2022-04-20 18:37:57,826 INFO [org.fly.cor.int.com.DbMigrate] (Quarkus Main Thread) Schema "public" is up to date. No migration necessary.
2022-04-20 18:37:58,813 INFO [io.quarkus] (Quarkus Main Thread) back-mcs-thirdparty 1.0.0-SNAPSHOT on JVM (powered by Quarkus 2.7.3.Final) started in 6.704s. Listening on: http://localhost:8080
2022-04-20 18:37:58,813 INFO [io.quarkus] (Quarkus Main Thread) Profile dev activated. Live Coding activated.
2022-04-20 18:37:58,813 INFO [io.quarkus] (Quarkus Main Thread) Installed features: [agroal, cdi, flyway, hibernate-orm, hibernate-orm-panache, jdbc-postgresql, narayana-jta, resteasy-jackson, resteasy-jsonb, smallrye-context-propagation, smallrye-graphql, vertx]
2022-04-20 18:38:04,408 INFO [graphqlIssueResource] (vert.x-worker-thread-0) ----------------------------------------2022-04-20 18:40:36,263 ERROR [io.sma.graphql] (vert.x-worker-thread-1) SRGQL012000: Data Fetching Error: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.mami.model.Issue
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:766)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:746)
at io.quarkus.hibernate.orm.runtime.session.TransactionScopedSession.persist(TransactionScopedSession.java:140)
at io.quarkus.hibernate.orm.runtime.session.ForwardingSession.persist(ForwardingSession.java:53)
at org.hibernate.Session_5b93bee577ae2f8d76647de04cfab36afbf52958_Synthetic_ClientProxy.persist(Unknown Source)
at io.quarkus.hibernate.orm.panache.common.runtime.AbstractJpaOperations.persist(AbstractJpaOperations.java:99)
at io.quarkus.hibernate.orm.panache.common.runtime.AbstractJpaOperations.persist(AbstractJpaOperations.java:94)
at io.quarkus.hibernate.orm.panache.PanacheRepositoryBase.persistAndFlush(PanacheRepositoryBase.java:81)
at com.mami.repository.IssueRepository_Subclass.persistAndFlush$$superforward1(Unknown Source)
at com.mami.repository.IssueRepository_Subclass$$function$$50.apply(Unknown Source)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.proceed(InvocationInterceptor.java:62)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.monitor(InvocationInterceptor.java:49)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor_Bean.intercept(Unknown Source)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
at com.mami.repository.IssueRepository_Subclass.persistAndFlush(Unknown Source)
at com.mami.repository.IssueRepository_ClientProxy.persistAndFlush(Unknown Source)
at com.mami.service.IssueService.createIssue(IssueService.java:29)
at com.mami.service.IssueService_Subclass.createIssue$$superforward1(Unknown Source)
at com.mami.service.IssueService_Subclass$$function$$6.apply(Unknown Source)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.proceed(InvocationInterceptor.java:62)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.monitor(InvocationInterceptor.java:49)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor_Bean.intercept(Unknown Source)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
at com.mami.service.IssueService_Subclass.createIssue(Unknown Source)
at com.mami.service.IssueService_ClientProxy.createIssue(Unknown Source)
at com.mami.resource.IssueResource.addIssue(IssueResource.java:48)
at com.mami.resource.IssueResource_Subclass.addIssue$$superforward1(Unknown Source)
at com.mami.resource.IssueResource_Subclass$$function$$2.apply(Unknown Source)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.proceed(InvocationInterceptor.java:62)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.monitor(InvocationInterceptor.java:49)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor_Bean.intercept(Unknown Source)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:50)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:132)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:103)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.doIntercept(TransactionalInterceptorRequired.java:38)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.intercept(TransactionalInterceptorBase.java:57)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.intercept(TransactionalInterceptorRequired.java:32)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired_Bean.intercept(Unknown Source)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
at com.mami.resource.IssueResource_Subclass.addIssue(Unknown Source)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at io.smallrye.graphql.execution.datafetcher.helper.ReflectionInvoker.invoke(ReflectionInvoker.java:88)
at io.smallrye.graphql.execution.datafetcher.DefaultDataFetcher.invokeAndTransform(DefaultDataFetcher.java:37)
at io.smallrye.graphql.execution.datafetcher.AbstractDataFetcher.get(AbstractDataFetcher.java:53)
at graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentation.lambda$instrumentDataFetcher$0(DataLoaderDispatcherInstrumentation.java:87)
at graphql.execution.ExecutionStrategy.fetchField(ExecutionStrategy.java:279)
at graphql.execution.ExecutionStrategy.resolveFieldWithInfo(ExecutionStrategy.java:210)
at graphql.execution.ExecutionStrategy.resolveField(ExecutionStrategy.java:182)
at graphql.execution.AsyncSerialExecutionStrategy.lambda$execute$1(AsyncSerialExecutionStrategy.java:43)
at graphql.execution.Async.eachSequentiallyImpl(Async.java:80)
at graphql.execution.Async.eachSequentially(Async.java:69)
at graphql.execution.AsyncSerialExecutionStrategy.execute(AsyncSerialExecutionStrategy.java:38)
at graphql.execution.Execution.executeOperation(Execution.java:159)
at graphql.execution.Execution.execute(Execution.java:105)
at graphql.GraphQL.execute(GraphQL.java:613)
at graphql.GraphQL.parseValidateAndExecute(GraphQL.java:538)
at graphql.GraphQL.executeAsync(GraphQL.java:502)
at graphql.GraphQL.execute(GraphQL.java:433)
at io.smallrye.graphql.execution.ExecutionService.execute(ExecutionService.java:126)
at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLExecutionHandler.doRequest(SmallRyeGraphQLExecutionHandler.java:299)
at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLExecutionHandler.handlePost(SmallRyeGraphQLExecutionHandler.java:113)
at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLExecutionHandler.doHandle(SmallRyeGraphQLExecutionHandler.java:73)
at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLAbstractHandler.handleWithIdentity(SmallRyeGraphQLAbstractHandler.java:66)
at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLAbstractHandler.handle(SmallRyeGraphQLAbstractHandler.java:48)
at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLAbstractHandler.handle(SmallRyeGraphQLAbstractHandler.java:23)
at io.vertx.ext.web.impl.BlockingHandlerDecorator.lambda$handle$0(BlockingHandlerDecorator.java:48)
at io.vertx.core.impl.ContextImpl.lambda$null$0(ContextImpl.java:159)
at io.vertx.core.impl.AbstractContext.dispatch(AbstractContext.java:100)
at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:157)
at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29)
at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.mami.model.Issue
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:120)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:760)
... 88 more
This is the Enity class:
#Entity
#Table(name = "issue")
public class Issue {
#Id
#GeneratedValue (strategy = GenerationType.AUTO)
#Column(name = "request_id", nullable = false)
private Long request_id;
#Column(name = "mideviceidissue")
private int miDeviceIdIssue;
#Column(name = "subject")
private String subject;
#Column(name = "description")
private String description;
#Column(name = "creationtime")
private String creationTime;
#Column(name = "status")
private String status;
#Column(name = "lastupdate")
private String lastUpdate;
public Long getRequest_id() {
return request_id;
}
public void setRequest_id(Long requestId) {
this.request_id = requestId;
}
public int getMiDeviceIdIssue() {
return miDeviceIdIssue;
}
public void setMiDeviceIdIssue(int miDeviceIdIssue) {
this.miDeviceIdIssue = miDeviceIdIssue;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCreationTime() {
return creationTime;
}
public void setCreationTime(String creationTime) {
this.creationTime = creationTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public Issue() { }
public Issue(Long request_id, int miDeviceIdIssue, String subject, String description, String creationTime, String status, String lastUpdate) {
this.request_id = request_id;
this.miDeviceIdIssue = miDeviceIdIssue;
this.subject = subject;
this.description = description;
this.creationTime = creationTime;
this.status = status;
this.lastUpdate = lastUpdate;
}
}
The Issue interface:
public interface McsPublicIssueInterface {
List<Issue> findAllIssues();
void createIssue(Issue issueToCreate);
Issue updateIssue(Long request_id, String status, String description);
boolean removeIssue(Long request_id);
}
The Issue Repository:
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import javax.enterprise.context.ApplicationScoped;
#ApplicationScoped
public class IssueRepository implements PanacheRepository<Issue> {
}
The Issue Service:
#ApplicationScoped
public class IssueService implements McsPublicIssueInterface {
#Inject
EntityManager entityManager;
#Inject
IssueRepository isRepo;
#Override
public List<Issue> findAllIssues() {
return isRepo.listAll();
}
#Override
public void createIssue(Issue issueToCreate) {
isRepo.persistAndFlush(issueToCreate);
}
#Override
public Issue updateIssue(Long request_id, String status, String description) {
Issue x = isRepo.findById(request_id);
x.setDescription(description);
x.setStatus(status);
return x;
}
#Override
public boolean removeIssue(Long request_id) {
return isRepo.deleteById(request_id);
}
}
The Issue Resource:
#GraphQLApi
public class IssueResource {
private static final Logger LOG = Logger.getLogger(IssueResource.class);
#LoggerName("graphqlIssueResource")
Logger log;
#Inject
private IssueRepository issueRepository;
#Inject
IssueService issueService;
#Inject
CurrentVertxRequest requestIssue;
#Query("issues")
#Description("Getting the whole issues")
public List<Issue> selectAllIssues() {
log.info("------------------------------------------- HERE IS CALLING TO GET ALL THE ISSUES ------------------");
return issueService.findAllIssues();
}
#Mutation("creatingNewIssue")
#Transactional
#Description("Creating a New Issue")
public Issue addIssue(Issue issueToCreate) {
issueService.createIssue(issueToCreate);
return issueToCreate;
}
#Mutation("updatingExistingIssue")
#Transactional
#Description("Updating Status and Description issue by request_id")
public Issue updateExistingIssue(#Name("request_id") Long request_id,
#Name("status") String status,
#Name("description") String description) {
return issueService.updateIssue(request_id, status, description);
}
#Mutation("deletingIssue")
#Transactional
#Description("Deleting specific issue by request_id")
public boolean deletePerson(Long request_id) {
return issueService.removeIssue(request_id);
}
}
This is the DB's table:
Issue table in DB / pgadmin4
Here how I test that addNew mutation:
enter image description here

How to identify the path of the infinispan configuration xml file

I am a newbie to infinispan and would like to seek help about issue below.
I tried to start a infinispan cache on an ejb, such that it should be shared among several applications.
#Singleton
public class CSysAppCacheServiceImpl implements CSysAppCacheService {
private DefaultCacheManager cacheManager;
private Cache testingCache;
#EJB(name = "postService")
private CSysPostDao postService;
#EJB(name = "roleService")
private CSysRoleDao roleService;
protected Map<String, List<CSysRole>> sysRoleMap;
protected Map<String, List<CSysPost>> sysPostMap;
protected List<CSysRole> sysRoleList;
protected List<CSysPost> sysPostList;
#PostConstruct
public void init() {
// perform some initialization logic
try {
System.out.println("init CacheManager start");
cacheManager = new DefaultCacheManager("/demo-infinispan.xml");
System.out.println("init CacheManager end");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
testingCache = cacheManager.getCache("testingCache");
preloadCache();
}
// Pre-load cache when server startup
public void preloadCache() {
for (CacheKey ck : CacheKey.values()) {
resetCache(ck);
}
}
public void resetCache(CacheKey key) {
if (key == null) {
for (CacheKey ck : CacheKey.values()) {
resetCache(ck);
}
} else if (key.equals(CacheKey.SYS_ROLE_LIST)) {
this.sysRoleList = roleService.findAllRole();
setupCacheList(CacheKey.SYS_ROLE_LIST, sysRoleList);
} else if (key.equals(CacheKey.SYS_POST_LIST)) {
this.sysPostList = postService.findAllPost();
setupCacheList(CacheKey.SYS_POST_LIST, sysPostList);
}
}
protected <T> void setupCacheList(CacheKey key, List<T> list) {
testingCache.put(key, list);
}
public List<Object> getCacheList(CacheKey key) {
return (List<Object>) testingCache.get(key);
}
public List<Object> getCacheList(String keyString) {
return (List<Object>) testingCache.get(keyString);
}
#SuppressWarnings("unchecked")
public <K, V> Map<K, V> getCacheMap(CacheKey key) {
return (Map<K, V>) testingCache.get(key);
}
public Map<String, List<CSysRole>> getCSysRoleMap() {
sysRoleMap = getCacheMap(CacheKey.SYS_ROLE_LIST);
if (MapUtils.isEmpty(sysRoleMap)) {
resetCache(CacheKey.SYS_ROLE_LIST);
}
return sysRoleMap;
}
public Map<String, List<CSysPost>> getCSysPostMap() {
sysRoleMap = getCacheMap(CacheKey.SYS_POST_LIST);
if (MapUtils.isEmpty(sysPostMap)) {
resetCache(CacheKey.SYS_POST_LIST);
}
return sysPostMap;
}
}
The ejb is init via following class
#ViewScoped
#Named
public class CacheView implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = LogManager.getLogger(CacheView.class);
public static final String FNCT_ID = "SAMPLCACH";
private List<String> cacheKeyList;
// private Map<K, V> selectedMap;
private CacheKey selectedKey;
private List<Object> selectedList;
#EJB CSysAppCacheService appScopeCache;
#PostConstruct
public void init() {
appScopeCache.init();
}
...
}}}}
But when the application start, following exception raised
Caused by: java.lang.NoClassDefFoundError: org/jboss/marshalling/ClassResolver
at org.infinispan.configuration.global.SerializationConfiguration.<clinit>(SerializationConfiguration.java:16)
at org.infinispan.configuration.global.SerializationConfigurationBuilder.<init>(SerializationConfigurationBuilder.java:27)
at org.infinispan.configuration.global.GlobalConfigurationBuilder.<init>(GlobalConfigurationBuilder.java:43)
at org.infinispan.configuration.parsing.ConfigurationBuilderHolder.<init>(ConfigurationBuilderHolder.java:25)
at org.infinispan.configuration.parsing.ParserRegistry.parse(ParserRegistry.java:122)
at org.infinispan.manager.DefaultCacheManager.<init>(DefaultCacheManager.java:311)
at org.infinispan.manager.DefaultCacheManager.<init>(DefaultCacheManager.java:286)
at org.infinispan.manager.DefaultCacheManager.<init>(DefaultCacheManager.java:274)
at CSysAppCacheServiceImpl.init(CSysAppCacheServiceImpl.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.as.ee.component.ManagedReferenceLifecycleMethodInterceptor.processInvocation(ManagedReferenceLifecycleMethodInterceptor.java:96)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.weld.interceptors.Jsr299BindingsInterceptor.doLifecycleInterception(Jsr299BindingsInterceptor.java:122)
at org.jboss.as.weld.interceptors.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:111)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:509)
at org.jboss.weld.module.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:72)
at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:89)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.weld.injection.WeldInjectionInterceptor.processInvocation(WeldInjectionInterceptor.java:53)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ee.component.ManagedReferenceFieldInjectionInterceptorFactory$ManagedReferenceFieldInjectionInterceptor.processInvocation(ManagedReferenceFieldInjectionInterceptorFactory.java:112)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ee.component.ManagedReferenceFieldInjectionInterceptorFactory$ManagedReferenceFieldInjectionInterceptor.processInvocation(ManagedReferenceFieldInjectionInterceptorFactory.java:112)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ee.component.AroundConstructInterceptorFactory$1.processInvocation(AroundConstructInterceptorFactory.java:28)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.weld.injection.WeldInterceptorInjectionInterceptor.processInvocation(WeldInterceptorInjectionInterceptor.java:56)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.weld.interceptors.Jsr299BindingsCreateInterceptor.processInvocation(Jsr299BindingsCreateInterceptor.java:105)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:237)
... 150 more
The problem should be at line
cacheManager = new DefaultCacheManager("/demo-infinispan.xml");
the xml is just a simple standlone cache as below
<?xml version="1.0" encoding="UTF-8"?>
<infinispan
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:infinispan:config:9.0 http://www.infinispan.org/schemas/infinispan-config-9.0.xsd"
xmlns="urn:infinispan:config:9.0">
<cache-container name="testing" default-cache="default">
<local-cache name="default">
<eviction max-entries="5000" strategy="LIRS" />
</local-cache>
</cache-container>
</infinispan>
I tried to put the demo-infinispan.xml in either of the following path, but still exception raised
1) same folder of the java bean
2) src folder of the package
3) same folder of the view bean
Would anyone advise where the xml should I put?
Thanks.
Best Regards,
The issue is solved due to missing libraries

Bulk operations in CassandraRepository for spring-data-cassandra 2.0M1

I have a simple spring-data-cassandra project that tries to insert multiple entities using
<S extends T> Iterable<S> save(Iterable<S> entities)
of the CassandraRepository class.
However when I use version 2.0.0.M1 (works in previous versions), I get the following error,
Exception in thread "main" org.springframework.data.cassandra.mapping.VerifierMappingExceptions: java.util.ArrayList:
- Cassandra entities must be annotated with either #Persistent, #Table, #UserDefinedType or #PrimaryKeyClass
at org.springframework.data.cassandra.mapping.CompositeCassandraPersistentEntityMetadataVerifier$PersistentAnnotationVerifier.verify(CompositeCassandraPersistentEntityMetadataVerifier.java:92)
at org.springframework.data.cassandra.mapping.CompositeCassandraPersistentEntityMetadataVerifier.verify(CompositeCassandraPersistentEntityMetadataVerifier.java:70)
at org.springframework.data.cassandra.mapping.BasicCassandraPersistentEntity.verify(BasicCassandraPersistentEntity.java:160)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:332)
at org.springframework.data.cassandra.mapping.BasicCassandraMappingContext.addPersistentEntity(BasicCassandraMappingContext.java:381)
at org.springframework.data.cassandra.mapping.BasicCassandraMappingContext.addPersistentEntity(BasicCassandraMappingContext.java:65)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:185)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:145)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:70)
at org.springframework.data.cassandra.core.CassandraTemplate.getPersistentEntity(CassandraTemplate.java:427)
at org.springframework.data.cassandra.core.CassandraTemplate.getTableName(CassandraTemplate.java:443)
at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:314)
at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:302)
at org.springframework.data.cassandra.repository.support.SimpleCassandraRepository.save(SimpleCassandraRepository.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.executeMethodOn(RepositoryFactorySupport.java:553)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:538)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:479)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy34.save(Unknown Source)
My main class, App.java
public class App
{
public static void main(String[] args) {
ApplicationContext context =new AnnotationConfigApplicationContext(CassandraConfig.class);
CustomerRepo repo=context.getBean(CustomerRepo.class);
List<Customer> customers=new ArrayList<Customer>();
Customer cust=new Customer();
cust.SetId("142");
cust.setName("Mayor");
cust.setAcc_type("new");
cust.setAcc_name("savings");
cust.setSegment("Normal");
customers.add(cust);
Customer cust1 = new Customer();
cust1.SetId("143");
cust1.setName("Final");
cust1.setAcc_type("new");
cust1.setAcc_name("savings");
cust1.setSegment("Normal");
customers.add(cust1);
repo.save(customers);
}
}
The entity class, Customer.java
#Table(value="Customer")
public class Customer {
#PrimaryKeyColumn(name = "id",ordinal = 1,type = PrimaryKeyType.PARTITIONED)
private String id;
#Column(value ="name")
private String name;
#Column(value = "acc_name")
private String acc_name;
#Column(value = "acc_type")
private String acc_type;
#Column(value = "segment")
private String segment;
public Customer(String id, String name, String acc_name, String acc_type,
String segment) {
this.id=id;
this.name=name;
this.acc_name=acc_name;
this.acc_type=acc_type;
this.segment=segment;
}
public Customer() {
}
public void SetId(String id)
{
this.id=id;
}
public void setName(String name)
{
this.name=name;
}
public void setAcc_name(String acc_name)
{
this.acc_name=acc_name;
}
public void setAcc_type(String acc_type)
{
this.acc_type=acc_type;
}
public void setSegment(String segment)
{
this.segment=segment;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getAcc_name() {
return acc_name;
}
public String getAcc_type() {
return acc_type;
}
public String getSegment() {
return segment;
}
}
And finally, the repository, CustomerRepo.java
import com.Entity.Customer;
public interface CustomerRepo extends CassandraRepository<Customer> {
}
Is this an issue (I haven't been able to find via Goolge or the site), or am I missing some annotations ?
For batch queries, use CassandraTemplate helps to insert batch of operations with multiple entities. This is available with Spring Data Cassandra.
example code:
CassandraBatchOperations batchOps = cassandraTemplate.batchOps();
batchOps(movieByGenre);
batchOps(movieByActor);
batchOps.insert(movie);
batchOps.execute();
This will use Cassandra native Batch operation internally.

Static method call from Eclipse Plugin: InjectionException

I have 2 plugin projects - generator.ui and generator.core.
The generator.ui depends on generator.core plugin for processes and data manipulation. However wherever there is an API call on generator.core (through static method invocation), I get an exception mentioned below:
org.eclipse.e4.core.di.InjectionException: java.lang.NoClassDefFoundError: de/upb/crc901/serge/generator/Generator
at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:63)
at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:243)
at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:224)
at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132)
at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:167)
at org.eclipse.core.commands.Command.executeWithChecks(Command.java:499)
at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:213)
at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.executeItem(HandledContributionItem.java:850).........
Caused by: java.lang.ClassNotFoundException: de.upb.crc901.serge.generator.Generator cannot be found by de.upb.crc901.serge.ui_1.0.0.qualifier
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:501)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:421)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:412)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(Unknown Source)
Now this NoClassDefFoundError always comes for the class which contains static method for object creation as the design pattern followed is "Singleton".
Any help would be greatly appreciated.
Here is the code, From the UI plugin; the configuration hub class:
public class ConfigurationHub implements IConfigurationHub {
private IGenerator generator;
private static IConfigurationHub configurationHub;
/*
* Constructor private to make Singleton
*/
private ConfigurationHub() {
generator = GeneratorFactory.createGenerator(Generator.class);
}
public static synchronized IConfigurationHub getInstance() {
if(null == configurationHub) {
configurationHub = new ConfigurationHub();
}
return configurationHub;
}
}
The GeneratorFactory class is in Generator plugin:
public class GeneratorFactory {
private GeneratorFactory() {}
public static <T extends IGenerator> T createGenerator(Class<T> type) {
try {
return (T) type.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
}
Regards,
Sid

UserTransaction failed when call utx.begin() throws "java.lang.IllegalStateException: Operation not allowed"

i want to use ejb and jpa controller, in netbeans the controller is generated automatically... I try to call the jpa controller from class (UniversidadServiceEJB) that is a session bean stateless, I debugged the project and the UserTransaction and EntityManagerFactory is created successfully but when call the method utx.begin in the jpa controller (UniversityJpaController) throws this exception:
java.lang.IllegalStateException: Operation not allowed.
at com.sun.enterprise.transaction.UserTransactionImpl.checkUserTransactionMethodAccess(UserTransactionImpl.java:146)
at com.sun.enterprise.transaction.UserTransactionImpl.begin(UserTransactionImpl.java:162)
at controller.UniversidadJpaController.create(UniversidadJpaController.java:47)
at services.UniversidadServiceEJB.create(UniversidadServiceEJB.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5388)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
...
...
...
The Session Bean class is:
#Stateless(name="UniversidadJpa")
#Remote(IGestionUniversidad.class)
public class UniversidadServiceEJB {
#Resource
private UserTransaction utx;
#PersistenceUnit(unitName="ApplicationEJBPU")
EntityManagerFactory emf;
public void create(Universidad universidad) throws Exception {
try {
UniversidadJpaController universidadController = new UniversidadJpaController(utx,emf);
universidadController.create(universidad);
} catch (RollbackFailureException ex) {
Logger.getLogger(UniversidadServiceEJB.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(UniversidadServiceEJB.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And the jpacontroller class is:
public class UniversidadJpaController implements Serializable {
public UniversidadJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Universidad universidad) throws RollbackFailureException, Exception {
if (universidad.getEstudiantes() == null) {
universidad.setEstudiantes(new ArrayList<Estudiante>());
}
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
List<Estudiante> attachedEstudiantes = new ArrayList<Estudiante>();
for (Estudiante estudiantesEstudianteToAttach : universidad.getEstudiantes()) {
estudiantesEstudianteToAttach = em.getReference(estudiantesEstudianteToAttach.getClass(), estudiantesEstudianteToAttach.getId());
attachedEstudiantes.add(estudiantesEstudianteToAttach);
}
universidad.setEstudiantes(attachedEstudiantes);
em.persist(universidad);
for (Estudiante estudiantesEstudiante : universidad.getEstudiantes()) {
Universidad oldUniversidadOfEstudiantesEstudiante = estudiantesEstudiante.getUniversidad();
estudiantesEstudiante.setUniversidad(universidad);
estudiantesEstudiante = em.merge(estudiantesEstudiante);
if (oldUniversidadOfEstudiantesEstudiante != null) {
oldUniversidadOfEstudiantesEstudiante.getEstudiantes().remove(estudiantesEstudiante);
oldUniversidadOfEstudiantesEstudiante = em.merge(oldUniversidadOfEstudiantesEstudiante);
}
}
utx.commit();
} catch (Exception ex) {
// try {
// utx.rollback();
// } catch (Exception re) {
// throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
// }
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
}
And the Persistence Unit is:
<?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="ApplicationEJBPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>sqlServer</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
Please what is the problem?..
Thank you very much...
Usually in an EJB Environment, the transaction is managed by the the container. It wraps the Bean methods in transactions with automatic rollback when an exception occurs. This also means that manually starting/committing/rollback a Transaction is not allowed and throws an IllegalStateException.
Reference: http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Transaction3.html
As posted above, under a Container Managed Transaction (CMT) you will get the getStatus() exception if you use the API.
https://issues.jboss.org/browse/JBSEAM-456
But you can as an alternative use:
#Resource
TransactionSynchronizationRegistry
How to tell if a transaction is active in a Java EE 6 interceptor?
By the way - the getStatus() api blows on glassfish, but it does not blow up on weblogic 12.1.2.
Weblogic should actually be throwing the exception on the get status api.
The
#Resource
TransactionSynchronizationRegistry
Works fine on both containers.