I'm getting ResourceException: Transaction is not active - java

I'm using Jboss Version 5.2.0.GA and I'm getting Transaction is not active when updating the status of a record in DB using hql.
DB connections are not exhausted, other requests are fulfilled by DB, I believe transaction is expired!
if 300 is increased in transaction-jboss-beans.xml will it help ?
2016-05-23 10:37:11,722 - ERROR - TestDAO.java : updateRecord (490) - updateRecord() Exception Message Cannot open connection
org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:126)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:114)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
at org.hibernate.jdbc.AbstractBatcher.prepareSelectStatement(AbstractBatcher.java:145)
at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1034)
at org.hibernate.engine.StatefulPersistenceContext.getDatabaseSnapshot(StatefulPersistenceContext.java:268)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:212)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:534)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:102)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:92)
at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:537)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:529)
at org.hibernate.engine.CascadingAction$5.cascade(CascadingAction.java:241)
at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:302)
at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:246)
at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:195)
at org.hibernate.engine.Cascade.cascade(Cascade.java:154)
at org.hibernate.engine.Cascade.cascade(Cascade.java:121)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.cascadeOnUpdate(DefaultSaveOrUpdateEventListener.java:379)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:351)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:245)
at org.hibernate.event.def.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:92)
at org.hibernate.impl.SessionImpl.fireUpdate(SessionImpl.java:594)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:582)
at com.abc.xyz.dao.SendSmsDAO.updateSendSms(SendSmsDAO.java:479)
at com.abc.xyz.transport.smpp.SMPPTransport.submitShortMessages(SMPPTransport.java:809)
at com.abc.xyz.transport.smpp.SMPPTransport.submit(SMPPTransport.java:647)
at com.abc.xyz.listeners.SendSmsMDB.onMessage(SendSmsMDB.java:202)
at sun.reflect.GeneratedMethodAccessor845.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.invocation.Invocation.performCall(Invocation.java:386)
at org.jboss.ejb.MessageDrivenContainer$ContainerInterceptor.invoke(MessageDrivenContainer.java:518)
at org.jboss.resource.connectionmanager.CachedConnectionInterceptor.invoke(CachedConnectionInterceptor.java:156)
at org.jboss.ejb.plugins.MessageDrivenInstanceInterceptor.invoke(MessageDrivenInstanceInterceptor.java:115)
at org.jboss.ejb.plugins.CallValidationInterceptor.invoke(CallValidationInterceptor.java:63)
at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInterceptor.java:121)
at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxInterceptorCMT.java:350)
at org.jboss.ejb.plugins.TxInterceptorCMT.invoke(TxInterceptorCMT.java:181)
at org.jboss.ejb.plugins.RunAsSecurityInterceptor.process(RunAsSecurityInterceptor.java:139)
at org.jboss.ejb.plugins.RunAsSecurityInterceptor.invoke(RunAsSecurityInterceptor.java:103)
at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:205)
at org.jboss.ejb.plugins.ProxyFactoryFinderInterceptor.invoke(ProxyFactoryFinderInterceptor.java:138)
at org.jboss.ejb.MessageDrivenContainer.internalInvoke(MessageDrivenContainer.java:420)
at org.jboss.ejb.Container.invoke(Container.java:1092)
at sun.reflect.GeneratedMethodAccessor786.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
at org.jboss.invocation.local.LocalInvoker$MBeanServerAction.invoke(LocalInvoker.java:169)
at org.jboss.invocation.local.LocalInvoker.invoke(LocalInvoker.java:118)
at org.jboss.invocation.InvokerInterceptor.invokeLocal(InvokerInterceptor.java:209)
at org.jboss.invocation.InvokerInterceptor.invoke(InvokerInterceptor.java:195)
at org.jboss.proxy.TransactionInterceptor.invoke(TransactionInterceptor.java:61)
at org.jboss.ejb.plugins.inflow.MessageEndpointInterceptor.delivery(MessageEndpointInterceptor.java:249)
at org.jboss.ejb.plugins.inflow.MessageEndpointInterceptor.invoke(MessageEndpointInterceptor.java:128)
at org.jboss.proxy.ClientMethodInterceptor.invoke(ClientMethodInterceptor.java:74)
at org.jboss.proxy.ClientContainer.invoke(ClientContainer.java:101)
at $Proxy1791.onMessage(Unknown Source)
at org.jboss.resource.adapter.jms.inflow.JmsServerSession.onMessage(JmsServerSession.java:179)
at org.jboss.jms.client.container.ClientConsumer.callOnMessageStatic(ClientConsumer.java:167)
at org.jboss.jms.client.container.SessionAspect.handleRun(SessionAspect.java:879)
at org.jboss.aop.advice.org.jboss.jms.client.container.SessionAspect_z_handleRun_1017119892.invoke(SessionAspect_z_handleRun_1017119892.java)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102)
at org.jboss.jms.client.container.ClosedInterceptor.invoke(ClosedInterceptor.java:172)
at org.jboss.aop.advice.PerInstanceInterceptor.invoke(PerInstanceInterceptor.java:86)
at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102)
at org.jboss.jms.client.delegate.ClientSessionDelegate.run(ClientSessionDelegate.java)
at org.jboss.jms.client.JBossSession.run(JBossSession.java:199)
at org.jboss.resource.adapter.jms.inflow.JmsServerSession.run(JmsServerSession.java:236)
at org.jboss.resource.work.WorkWrapper.execute(WorkWrapper.java:205)
at org.jboss.util.threadpool.BasicTaskWrapper.run(BasicTaskWrapper.java:260)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.jboss.util.NestedSQLException: Transaction is not active: tx=TransactionImple < ac, BasicAction: a1c162a:994a:5742b99a:169b status: ActionStatus.ABORTED >; - nested throwable: (javax.resource.ResourceException: Transaction is not active: tx=TransactionImple < ac, BasicAction: a1c162a:994a:5742b99a:169b status: ActionStatus.ABORTED >)
at org.jboss.resource.adapter.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:95)
at org.hibernate.connection.DatasourceConnectionProvider.getConnection(DatasourceConnectionProvider.java:91)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
... 78 more
Caused by: javax.resource.ResourceException: Transaction is not active: tx=TransactionImple < ac, BasicAction: a1c162a:994a:5742b99a:169b status: ActionStatus.ABORTED >
at org.jboss.resource.connectionmanager.TxConnectionManager.getManagedConnection(TxConnectionManager.java:413)
at org.jboss.resource.connectionmanager.BaseConnectionManager2.allocateConnection(BaseConnectionManager2.java:496)
at org.jboss.resource.connectionmanager.BaseConnectionManager2$ConnectionManagerProxy.allocateConnection(BaseConnectionManager2.java:941)
at org.jboss.resource.adapter.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:89)
... 80 more
Regards,
Nithesh

Could you post your line code? I dont know if you are using annotation to controls the transactions so maybe using entityManager.getTransaction.begin() before you do the merge could solve the problem.

I'm not using Jboss transactions, I'm using hibernate transactions, please find the code below.
public void persistStatus(Status transientInstance){
logger.debug("persisting into DB");
org.hibernate.Transaction transaction = null;
try
{
openSession();
transaction = session.beginTransaction();
session.persist(transientInstance);
transaction.commit();
logger.debug("persist successfully ");
}
catch (HibernateException re){
logger.error("Exception while inserting status "+re);
if(transaction!=null && transaction.isActive())
transaction.rollback();
closeActiveSession();
throw re;
}finally{
if (session != null && session.isOpen()) {
session.clear();
session.close();
}
}
}
I think Jboss internally handles transactions ?

Related

Hibernate Thread Hangs and never responds

I faced a weird issue and it is just like a dead-lock. When i call a dao method to save an entity into oracle db, hibernate never respond and thread never comes back. My aim is to save a row when exception is cached. However, Hibernate neither throws exception nor do its job. Just waiting forever(Thread has been waiting for 3 days). Is there any idea about the problem? what did i implement wrong?
Thread Dump is
java.lang.Thread.State: RUNNABLE
at sun.nio.ch.FileDispatcherImpl.read0(FileDispatcherImpl.java:-1)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:197)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
- locked <0x9cfc> (a java.lang.Object)
at oracle.net.nt.TimeoutSocketChannel.read(TimeoutSocketChannel.java:144)
at oracle.net.ns.NIOHeader.readHeaderBuffer(NIOHeader.java:82)
at oracle.net.ns.NIOPacket.readFromSocketChannel(NIOPacket.java:139)
at oracle.net.ns.NIOPacket.readFromSocketChannel(NIOPacket.java:101)
at oracle.net.ns.NIONSDataChannel.readDataFromSocketChannel(NIONSDataChannel.java:80)
at oracle.jdbc.driver.T4CMAREngineNIO.prepareForReading(T4CMAREngineNIO.java:98)
at oracle.jdbc.driver.T4CMAREngineNIO.unmarshalUB1(T4CMAREngineNIO.java:534)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:485)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:612)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:226)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:59)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:910)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1119)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3780)
at oracle.jdbc.driver.T4CPreparedStatement.executeInternal(T4CPreparedStatement.java:1343)
at oracle.jdbc.driver.OraclePreparedStatement.executeLargeUpdate(OraclePreparedStatement.java:3865)
- locked <0x9cfd> (a oracle.jdbc.driver.T4CConnection)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3845)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1061)
at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:121)
at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:121)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3224)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3126)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3456)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:140)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:364)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:356)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:278)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:328)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1234)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:584)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:765)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:734)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:518)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:671)
at com.xxx.yyy.zzz.PaymentTransactionService$$EnhancerBySpringCGLIB$$878a078.mergeWithNewTransaction(<generated>:-1)
at com.xxx.yyy.zzz.SavePaymentTransaction.process(SavePaymentTransaction.java:49)
class SavePaymentTransaction {
#Transactional
public void process(Entity e1){
try{
service.save(e1);// here throws exception
} catch(Exception e){
PaymentEntity pe = //createPaymentEntity
paymentTransactionService.mergeWithNewTransaction(pe);
// threads never comes back here and hangs when above line runs
}
}
}
class PaymentTransactionService {
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void mergeWithNewTransaction(PaymentEntity e1){
// this line is not shown in the thread dump
dao.save(e1);
}
}

Hibernate code checks if session is closed before commiting txn but then complains session is closed

I am using Hibernate (with H2 database), sometimes if a task takes too long I cancel it so the session associate with the task becomes invalid. I have a method typically used in finally blocks and this ensure txn is committed and session closed but only if sessions till open, and not rolled back.
public static void commitAndClose(Session session)
{
try
{
if (session!=null && session.isOpen() && !session.getTransaction().wasRolledBack())
{
if(session.getTransaction().isActive())
{
session.getTransaction().commit();
}
}
}
catch(Exception ex)
{
Errors.addError(ex.getMessage());
}
finally
{
if (session!=null && session.isOpen())
{
HibernateUtil.closeSession(session);
}
}
}
Yet for some reason it is trying to commit the txn and then complains it was closed, even though the closed check immediately beforehand was okay.
Is this just a timing issue ?
org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:196)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareStatement(StatementPreparerImpl.java:96)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3238)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3183)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3525)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:159)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:465)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:351)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at com.jthink.songkong.util.SessionUtil.commitAndClose(SessionUtil.java:32)
at com.jthink.songkong.analyse.analyser.MusicBrainzSongGroupMatcher1.doTask(MusicBrainzSongGroupMatcher1.java:448)
at com.jthink.songkong.analyse.analyser.MusicBrainzSongGroupMatcher.call(MusicBrainzSongGroupMatcher.java:469)
at com.jthink.songkong.analyse.analyser.MusicBrainzSongGroupMatcher1.call(MusicBrainzSongGroupMatcher1.java:83)
at com.jthink.songkong.analyse.analyser.MusicBrainzSongGroupMatcher1.call(MusicBrainzSongGroupMatcher1.java:37)
at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Caused by: org.h2.jdbc.JdbcSQLNonTransientException: The object is already closed [90007-199]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:502)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:427)
at org.h2.message.DbException.get(DbException.java:205)
at org.h2.message.DbException.get(DbException.java:181)
at org.h2.message.DbException.get(DbException.java:170)
at org.h2.jdbc.JdbcConnection.checkClosed(JdbcConnection.java:1568)
at org.h2.jdbc.JdbcConnection.checkClosed(JdbcConnection.java:1547)
at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:347)
at jdk.internal.reflect.GeneratedMethodAccessor34.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at com.mchange.v2.c3p0.stmt.GooGooStatementCache$1StmtAcquireTask.run(GooGooStatementCache.java:546)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)

Running transaction on different bean throws exception

I have asked this question and implemented the answer. It worked fine but now that I'm handling more data and it is not working as expected. Explaining:
I'm building integration with JMS. By the end of the integration process I must log the integration no matter what. To do so, I have build a #Service that saves a log in a new transaction. If I use the service, I'm getting an exception. If I execute the same logic of the service in the same bean it works fine. Let me show some code:
The listener
public class JMSListenerIntegration {
#Autowired
private IntegrationHandler integrationHandler;
#Autowired
private LogService logService;
#Autowired
private IntegrationLogRepository logRepository; // extends JpaRepository
#JmsListener(...)
public void onReceive(Message message) {
List<Dto> dtos = // Unmarshall the message
// A log for this integration already exists
// On receiving a message, it changes status from RUNNING to OK or NOK
IntegrationLog log = logRepository.findAlreadyExistingLog();
try {
// The integration handler persist 100+ records, each one in a new transaction
boolean success = integrationHandler.handle(dtos);
if (success)
log.setStatus("OK");
else
log.setStatus("NOK");
} catch (Exception e) {
log.setStatus("NOK");
} finally {
logService.save(log);
// this.saveLog(log); // THIS WORKS
}
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void saveLog(IntegrationLog log) {
logRepository.saveAndFlush(log);
}
}
LogService
#Service
public class LogService {
#Autowired
private IntegrationLogRepository logRepository;
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void save(IntegrationLog log) {
logRepository.saveAndFlush(log);
}
}
If I run the code using the saveLog() function defined on my JMSListenerIntegration it works fine. If, instead, I try to use my LogService class it does not work. I see on the log a hibernate query for selecting a log and then, after some good 20s, I get an error:
2019-01-02 20:21:35.649 WARN 21112 --- [ (self-tuning)'] onizationCallbackCoordinatorTrackingImpl : HHH000451: Transaction afterCompletion called by a background thread; delaying afterCompletion processing until the original thread can handle it. [status=4]
2019-01-02 20:21:35.652 WARN 21112 --- [enerContainer-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: null
2019-01-02 20:21:35.652 ERROR 21112 --- [enerContainer-1] o.h.engine.jdbc.spi.SqlExceptionHelper : The transaction is no longer active - status: 'Marked rollback. [Reason=weblogic.transaction.internal.TimedOutException: Transaction timed out after 31 seconds
BEA1-36996D3224E23057A4BD]'. No further JDBC access is allowed within this transaction.
2019-01-02 20:21:35.657 INFO 21112 --- [enerContainer-1] o.h.e.internal.DefaultLoadEventListener : HHH000327: Error performing load command : org.hibernate.exception.GenericJDBCException: could not load an entity: [com.example.models.IntegrationLog#6]
2019-01-02 20:21:35.692 WARN 21112 --- [enerContainer-1] o.s.j.l.DefaultMessageListenerContainer : Execution of JMS message listener failed, and no ErrorHandler has been set.
org.springframework.orm.jpa.JpaSystemException: could not load an entity: [com.example.models.IntegrationLog#6]; nested exception is org.hibernate.exception.GenericJDBCException: could not load an entity: [com.example.models.IntegrationLog#6]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:333) ~[spring-orm-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244) ~[spring-orm-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:525) ~[spring-orm-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:209) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.14.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.14.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at com.sun.proxy.$Proxy400.save(Unknown Source) ~[na:na]
at com.example.services.IntegrationLogService.save(IntegrationLogService.kt:20) ~[_wl_cls_gen.jar:na]
at com.example.services.IntegrationLogService$$FastClassBySpringCGLIB$$98a7fdd9.invoke(<generated>) ~[_wl_cls_gen.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:736) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:671) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at com.example.services.IntegrationLogService$$EnhancerBySpringCGLIB$$9eee6d68.save(<generated>) ~[_wl_cls_gen.jar:na]
at com.example.integrations.listeners.MalhaJmsListener.onReceive(MalhaJmsListener.kt:88) ~[_wl_cls_gen.jar:na]
at com.example.integrations.listeners.MalhaJmsListener$$FastClassBySpringCGLIB$$1357be2d.invoke(<generated>) ~[_wl_cls_gen.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:667) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at com.example.integrations.listeners.MalhaJmsListener$$EnhancerBySpringCGLIB$$c9de82e4.onReceive(<generated>) ~[_wl_cls_gen.jar:na]
at com.example.integrations.listeners.ListenersManager$startupListeners$1.onMessage(ListenersManager.kt:42) ~[_wl_cls_gen.jar:na]
at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:744) ~[spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:682) ~[spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:649) ~[spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:317) [spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:235) [spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1168) [spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1160) [spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:1057) [spring-jms-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_192]
Caused by: org.hibernate.exception.GenericJDBCException: could not load an entity: [com.example.models.IntegrationLog#6]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.Loader.loadEntity(Loader.java:2213) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:60) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:50) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4083) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1142) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl.access$2600(SessionImpl.java:167) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.doLoad(SessionImpl.java:2762) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2741) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:983) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:289) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:169) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:68) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:843) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:825) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:830) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1161) ~[hibernate-entitymanager-5.1.0.Final.jar:5.1.0.Final]
at sun.reflect.GeneratedMethodAccessor252.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_192]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_192]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347) ~[spring-orm-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at com.sun.proxy.$Proxy386.merge(Unknown Source) ~[na:na]
at sun.reflect.GeneratedMethodAccessor252.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_192]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_192]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:300) ~[spring-orm-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at com.sun.proxy.$Proxy386.merge(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:511) ~[spring-data-jpa-1.11.14.RELEASE.jar:na]
at sun.reflect.GeneratedMethodAccessor254.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_192]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_192]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:515) ~[spring-data-commons-1.13.14.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:500) ~[spring-data-commons-1.13.14.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:477) ~[spring-data-commons-1.13.14.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56) ~[spring-data-commons-1.13.14.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.18.RELEASE.jar:4.3.18.RELEASE]
... 35 common frames omitted
Caused by: java.sql.SQLException: The transaction is no longer active - status: 'Marked rollback. [Reason=weblogic.transaction.internal.TimedOutException: Transaction timed out after 30 seconds
BEA1-01E60652F53A3057A4BD]'. No further JDBC access is allowed within this transaction.
at weblogic.jdbc.wrapper.JTSConnection.checkIfRolledBack(JTSConnection.java:202) ~[weblogic.server.merged.jar:12.1.3.0.0]
at weblogic.jdbc.wrapper.JTSConnection.checkConnection(JTSConnection.java:220) ~[weblogic.server.merged.jar:12.1.3.0.0]
at weblogic.jdbc.wrapper.ResultSet.preInvocationHandler(ResultSet.java:95) ~[weblogic.server.merged.jar:12.1.3.0.0]
at weblogic.jdbc.wrapper.ResultSet_weblogic_jdbc_sqlserverbase_ddeb.next(Unknown Source) ~[weblogic.server.merged.jar:12.1.3.0.0]
at org.hibernate.loader.Loader.processResultSet(Loader.java:974) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.Loader.doQuery(Loader.java:936) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:312) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
at org.hibernate.loader.Loader.loadEntity(Loader.java:2209) ~[hibernate-core-5.1.16.Final.jar:5.1.16.Final]
... 81 common frames omitted
Any ideas on why this is happening?
Thanks,
EDIT
Following the comments suggestion I have changed my LogService to look like:
#Service
public class LogService {
#Autowired
private IntegrationLogRepository logRepository;
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void save(IntegrationLog plainLog) {
IntegrationLog log = logRepository.findOne(plainLog.getId());
log.setStatus(plainLog.getStatus());
log.setFoo(plainLog.getFoo());
// ...
logRepository.saveAndFlush(log);
}
}
And I still get the same error. And I start to think it is related to the previous operations done on integrationHandler.handle(dtos). In this method, I persist a lot of records. The logic looks like:
public boolean handle(List<Dto> dtos) {
boolean result = true;
for (Dto dto in dtos) {
try {
Foo foo = new Foo();
foo.setProp1(dto.getProp1());
foo.setProp2(dto.getProp2());
saveFoo(foo);
} catch (Exception e) {
logger.error(e.getMessage());
result = false;
}
}
return result;
}
// Now I know this is not running in its own transaction, right?
#Transactional(propagation = Propagation.REQUIRES_NEW)
public saveFoo(Foo foo) {
fooRepository.save(foo);
}
If I don't call the handle() method (so the persist operations are not performed) the LogService works just fine. I can only imagine the transaction for saving the Foo's are taking too long and the transaction for findOne is gettint timed out (can't find a reason why) giving the could not load an entity (I even tried calling findOne(6) which is a valid ID in my database). Maybe this is not the right way to persist the data...? Really lost here guys. Any help is appreciated :/

JPA RollbackException persist transaction causes subsequent valid transactions to fail?

I have a #Transactional service performing a persist action into an oracle DB. If i run a persist breaking a unique violation i get the expected rollbackException:ConstraintException.
The problem is that any subsequent request (even if not breaking the unique constraint) to persist throws the same exception.
It seems like JPA is not clearing the object to persist out of its transaction manager? Am i even close? I need a little explaination.
Repo:
#Repository
public class UserRepository {
#PersistenceContext(type=PersistenceContextType.EXTENDED)
private EntityManager em;
public User findUserById(long id){
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<User> query = builder.createQuery(User.class);
Root<User> root = query.from(User.class);
Predicate whereClause = builder.equal(root.get(User_.userId), id);
return em.createQuery(query.where(whereClause)).getSingleResult();
}
public User findUserByCredentials(String credentials){
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<User> query = builder.createQuery(User.class);
Root<User> root = query.from(User.class);
Predicate whereClause = builder.equal(root.get(User_.credentials), credentials);
return em.createQuery(query.where(whereClause)).getSingleResult();
}
public void registerUser(User user){
em.persist(user);
}
}
ServiceImpl:
#Transactional(readOnly=true)
#Service("userService")
public class UserServiceImpl implements UserService {
#Resource
private UserRepository userRepository;
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User findUserById(long id) {
return userRepository.findUserById(id);
}
public User findUserByCredentials(String credentials){
return userRepository.findUserByCredentials(credentials);
}
#Transactional(readOnly=false)
public void registerUser(User user){
userRepository.registerUser(user);
}
}
error throw in endpoint:
#PayloadRoot(localPart="RegisterUserRequest", namespace = "http://www.missingwire.com/schemas/User")
public RegisterUserResponseDocument registerUser(RegisterUserRequestDocument requestDoc){
RegisterUserRequest request = requestDoc.getRegisterUserRequest();
User user = new User();
user.setCredentials(request.getCredentials());
user.setPassword(request.getPassword());
user.setHonorRating(BigDecimal.valueOf(STARTING_USER_HONOR_RATING));
user.setAccountActive(true);
user.setDateCreated(new Date());
user.setVerified(false);
UserProfile userProfile = new UserProfile();
userProfile.setEmailAddress(request.getEmail());
userProfile.setFirstName(request.getFirstName());
userProfile.setLastName(request.getLastName());
userProfile.setDateCreated(new Date());
userProfile.setUser(user);
user.setUserProfile(userProfile);
**userService.registerUser(user);** //HERE IS THE EXCEPTION THROW
RegisterUserResponseDocument responseDoc = RegisterUserResponseDocument.Factory.newInstance();
RegisterUserResponse response = responseDoc.addNewRegisterUserResponse();
UserType userType = response.addNewUser();
userType.setAccountActive(user.getAccountActive());
userType.setCredentials(user.getCredentials());
userType.setDateCreated(DateConverter.convertDateToXML(user.getDateCreated()));
userType.setUserId(user.getUserId());
userType.setVerified(user.getVerified());
return responseDoc;
}
Exception:
org.springframework.orm.jpa.JpaSystemException: Error while committing
the transaction; nested exception is
javax.persistence.RollbackException: Error while committing the
transaction at
org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:311)
at
org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:102)
at
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerSynchronization.convertException(ExtendedEntityManagerCreator.java:501)
at
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerSynchronization.afterCommit(ExtendedEntityManagerCreator.java:481)
at
org.springframework.transaction.support.TransactionSynchronizationUtils.invokeAfterCommit(TransactionSynchronizationUtils.java:133)
at
org.springframework.transaction.support.TransactionSynchronizationUtils.triggerAfterCommit(TransactionSynchronizationUtils.java:121)
at
org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerAfterCommit(AbstractPlatformTransactionManager.java:953)
at
org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:796)
at
org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
at
org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
at
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy37.registerUser(Unknown Source) at
com.missingwire.achieve.soa.endpoint.UserEndpoint.registerUser(UserEndpoint.java:76)
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:616) at
org.springframework.ws.server.endpoint.MethodEndpoint.invoke(MethodEndpoint.java:132)
at
org.springframework.ws.server.endpoint.adapter.MarshallingMethodEndpointAdapter.invokeInternal(MarshallingMethodEndpointAdapter.java:140)
at
org.springframework.ws.server.endpoint.adapter.AbstractMethodEndpointAdapter.invoke(AbstractMethodEndpointAdapter.java:53)
at
org.springframework.ws.server.MessageDispatcher.dispatch(MessageDispatcher.java:231)
at
org.springframework.ws.server.MessageDispatcher.receive(MessageDispatcher.java:172)
at
org.springframework.ws.transport.support.WebServiceMessageReceiverObjectSupport.handleConnection(WebServiceMessageReceiverObjectSupport.java:88)
at
org.springframework.ws.transport.http.WebServiceMessageReceiverHandlerAdapter.handle(WebServiceMessageReceiverHandlerAdapter.java:57)
at
org.springframework.ws.transport.http.MessageDispatcherServlet.doService(MessageDispatcherServlet.java:221)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
at
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:585)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
at
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:679) Caused by:
javax.persistence.RollbackException: Error while committing the
transaction at
org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:93) at
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerSynchronization.afterCommit(ExtendedEntityManagerCreator.java:478)
... 39 more Caused by: javax.persistence.PersistenceException:
org.hibernate.exception.ConstraintViolationException: Could not
execute JDBC batch update at
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1235)
at
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1168)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:81)
... 40 more Caused by:
org.hibernate.exception.ConstraintViolationException: Could not
execute JDBC batch update at
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
at
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at
org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at
org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:114)
at
org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:109)
at
org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:244)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2395)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2858)
at
org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:267) at
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:259)
at
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:178)
at
org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at
org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206) at
org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:375) at
org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:76)
... 40 more Caused by: java.sql.BatchUpdateException: ORA-00001:
unique constraint (ACHIEVE.SYS_C0016488) violated
at
oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10070)
at
oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:213)
at
org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at
org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
You're injecting an entity manager for an extended persistence context. That means that the lifetime of the persistence context is not tied to the lifetime of the transaction: it stays open until you close it explicitely.
Since you got a RollbackException, the persistence context is in a dirty, inconsistent state, and the only thing you can do is close it immediately.
If the persistence context was a transactional one, it would be closed automatically. But since you're using an extended context, it's up to you to close it explicitely.
Make sure to read and understand the following section of the Spring documentation:
The #PersistenceContext annotation has an optional attribute type,
which defaults to PersistenceContextType.TRANSACTION. This default is
what you need to receive a shared EntityManager proxy. The
alternative, PersistenceContextType.EXTENDED, is a completely
different affair: This results in a so-called extended EntityManager,
which is not thread-safe and hence must not be used in a concurrently
accessed component such as a Spring-managed singleton bean. Extended
EntityManagers are only supposed to be used in stateful components
that, for example, reside in a session, with the lifecycle of the
EntityManager not tied to a current transaction but rather being
completely up to the application.
Adding:
#TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
To methods you want to exclude transactionallity (queries, for example), you'll avoid this problem.

Hibernate ConstraintViolationException in join table

I'm running into a ConstraintViolationException when I try to save an object with a #OneToMany map in it. Hibernate either seems to think that I'm trying to put a NULL into the mapped list or it may be putting it there itself. The problem seems to happen sporadically: with some databases it's easily reproducible, but with others I can't get it to happen at all.
I'm kind of a newbie at both Hibernate and Hibernate Annotations, so any help at all would be much appreciated.
I have two classes: Camera and AlarmZone (which extends a 3rd class, Zone). Among other things, Camera contains a list of IDs of AlarmZone objects. Here's the class declarations:
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
#Table(name = "cameras")
public class Camera
{
private Serializable id;
private List<Serializable> alarm_zones = new ArrayList<Serializable>();
...
#Id(generate = GeneratorType.SEQUENCE)
#Type(type = "java.lang.Long")
public java.io.Serializable getId()
{
return this.id;
}
public void setId(java.io.Serializable id)
{
this.id = id;
}
#OneToMany(targetEntity = java.lang.Long.class, fetch = FetchType.EAGER)
#JoinTable(table = #Table(name = "cameraalarmzones"))
public List<Serializable> getAlarmZones()
{
return alarm_zones;
}
public void setAlarmZones(List<Serializable> alarm_zones)
{
this.alarm_zones = alarm_zones;
}
...
}
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
#Table(name = "zones")
public class Zone
{
private Serializable id;
...
#Id(generate = GeneratorType.SEQUENCE)
#Type(type = "java.lang.Long")
public java.io.Serializable getId()
{
return this.id;
}
public void setId(java.io.Serializable id)
{
this.id = id;
}
}
#Entity
#Table(name = "alarmzones")
public class AlarmZone extends Zone
{
...
}
Whenever I save an object, I use what I understand to be boilerplate commit code:
public Persistable makePersistent(Object entity)
{
try
{
Hibernate.getSession().beginTransaction();
Hibernate.getSession().saveOrUpdate(entity);
Hibernate.getSession().flush();
Hibernate.getSession().getTransaction().commit();
} catch (RuntimeException e)
{
Hibernate.getSession().getTransaction().rollback();
logger.error("makePersistent(" + entity.getClass().getSimpleName()
+ ")", e);
}
return entity;
}
The problem happens when I save an AlarmZone, then put its ID into the Camera's list and try to save the camera. To get better debug info, I followed the advice from https://forum.hibernate.org/viewtopic.php?p=2220295&sid=a7ccc3be32137436c8062a99c8372a9e and set my batch size to be 0 and turned on DEBUG level debugging in log4j. Here's the stack trace for the error (along with the preceding few lines):
[2009-10-23 14:33:07,606] DEBUG [http-8443-Processor25] (AbstractCollectionPersister.java:947) - Deleting collection: [x.y.z.Camera.alarmZones#641]
[2009-10-23 14:33:07,606] DEBUG [http-8443-Processor25] (AbstractBatcher.java:311) - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
[2009-10-23 14:33:07,606] DEBUG [http-8443-Processor25] (AbstractBatcher.java:346) - delete from cameraalarmzones where cameras_id=?
[2009-10-23 14:33:07,606] DEBUG [http-8443-Processor25] (AbstractBatcher.java:424) - preparing statement
[2009-10-23 14:33:07,606] DEBUG [http-8443-Processor25] (NullableType.java:79) - binding '641' to parameter: 1
[2009-10-23 14:33:07,606] DEBUG [http-8443-Processor25] (AbstractCollectionPersister.java:977) - done deleting collection
[2009-10-23 14:33:07,606] DEBUG [http-8443-Processor25] (AbstractCollectionPersister.java:999) - Inserting collection: [x.y.z.Camera.alarmZones#641]
[2009-10-23 14:33:07,606] DEBUG [http-8443-Processor25] (AbstractBatcher.java:319) - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
[2009-10-23 14:33:07,606] DEBUG [http-8443-Processor25] (AbstractBatcher.java:470) - closing statement
[2009-10-23 14:33:07,606] DEBUG [http-8443-Processor25] (AbstractBatcher.java:311) - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
[2009-10-23 14:33:07,622] DEBUG [http-8443-Processor25] (AbstractBatcher.java:346) - insert into cameraalarmzones (cameras_id, elt) values (?, ?)
[2009-10-23 14:33:07,622] DEBUG [http-8443-Processor25] (AbstractBatcher.java:424) - preparing statement
[2009-10-23 14:33:07,622] DEBUG [http-8443-Processor25] (NullableType.java:79) - binding '641' to parameter: 1
[2009-10-23 14:33:07,622] DEBUG [http-8443-Processor25] (NullableType.java:79) - binding '649' to parameter: 2
[2009-10-23 14:33:07,622] DEBUG [http-8443-Processor25] (AbstractBatcher.java:319) - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
[2009-10-23 14:33:07,622] DEBUG [http-8443-Processor25] (AbstractBatcher.java:470) - closing statement
[2009-10-23 14:33:07,637] DEBUG [http-8443-Processor25] (JDBCExceptionReporter.java:63) - could not insert collection: [x.y.z.Camera.alarmZones#641] [insert into cameraalarmzones (cameras_id, elt) values (?, ?)]
java.sql.SQLException: Attempt to insert null into a non-nullable column: column: ALARMZONES table: CAMERAALARMZONES in statement [insert into cameraalarmzones (cameras_id, elt) values (?, ?)]
at org.hsqldb.jdbc.Util.throwError(Unknown Source)
at org.hsqldb.jdbc.jdbcPreparedStatement.executeUpdate(Unknown Source)
at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:23)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1039)
at org.hibernate.action.CollectionUpdateAction.execute(CollectionUpdateAction.java:51)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:243)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:227)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:143)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:296)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:980)
at sun.reflect.GeneratedMethodAccessor56.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:292)
at $Proxy25.flush(Unknown Source)
at com.silkspeed.ssparts.server.PersistableDAOImpl.makePersistent(PersistableDAOImpl.java:82)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:292)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:155)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:122)
at org.springframework.remoting.support.RemoteInvocationTraceInterceptor.invoke(RemoteInvocationTraceInterceptor.java:68)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:144)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:174)
at $Proxy38.makePersistent(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.remoting.support.RemoteInvocation.invoke(RemoteInvocation.java:179)
at org.springframework.remoting.support.DefaultRemoteInvocationExecutor.invoke(DefaultRemoteInvocationExecutor.java:33)
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invoke(RemoteInvocationBasedExporter.java:76)
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invokeAndCreateResult(RemoteInvocationBasedExporter.java:112)
at org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter.handleRequest(HttpInvokerServiceExporter.java:80)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:44)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:684)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:625)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:392)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:357)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at x.y.z.server.SessionInfo.doFilter(SessionInfo.java:91)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:525)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:151)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:874)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Thread.java:619)
[2009-10-23 14:33:07,637] WARN [http-8443-Processor25] (JDBCExceptionReporter.java:71) - SQL Error: -10, SQLState: 23000
[2009-10-23 14:33:07,637] ERROR [http-8443-Processor25] (JDBCExceptionReporter.java:72) - Attempt to insert null into a non-nullable column: column: ALARMZONES table: CAMERAALARMZONES in statement [insert into cameraalarmzones (cameras_id, elt) values (?, ?)]
[2009-10-23 14:33:07,637] ERROR [http-8443-Processor25] (AbstractFlushingEventListener.java:299) - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: could not insert collection: [x.y.z.Camera.alarmZones#641]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:69)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1058)
at org.hibernate.action.CollectionUpdateAction.execute(CollectionUpdateAction.java:51)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:243)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:227)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:143)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:296)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:980)
at sun.reflect.GeneratedMethodAccessor56.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:292)
at $Proxy25.flush(Unknown Source)
at com.silkspeed.ssparts.server.PersistableDAOImpl.makePersistent(PersistableDAOImpl.java:82)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:292)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:155)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:122)
at org.springframework.remoting.support.RemoteInvocationTraceInterceptor.invoke(RemoteInvocationTraceInterceptor.java:68)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:144)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:174)
at $Proxy38.makePersistent(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.remoting.support.RemoteInvocation.invoke(RemoteInvocation.java:179)
at org.springframework.remoting.support.DefaultRemoteInvocationExecutor.invoke(DefaultRemoteInvocationExecutor.java:33)
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invoke(RemoteInvocationBasedExporter.java:76)
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invokeAndCreateResult(RemoteInvocationBasedExporter.java:112)
at org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter.handleRequest(HttpInvokerServiceExporter.java:80)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:44)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:684)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:625)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:392)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:357)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at x.y.z.server.SessionInfo.doFilter(SessionInfo.java:91)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:525)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:151)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:874)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.sql.SQLException: Attempt to insert null into a non-nullable column: column: ALARMZONES table: CAMERAALARMZONES in statement [insert into cameraalarmzones (cameras_id, elt) values (?, ?)]
at org.hsqldb.jdbc.Util.throwError(Unknown Source)
at org.hsqldb.jdbc.jdbcPreparedStatement.executeUpdate(Unknown Source)
at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:23)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1039)
... 58 more
[2009-10-23 14:33:07,637] DEBUG [http-8443-Processor25] (JDBCTransaction.java:152) - rollback
[2009-10-23 14:33:07,637] DEBUG [http-8443-Processor25] (JDBCTransaction.java:193) - re-enabling autocommit
[2009-10-23 14:33:07,637] DEBUG [http-8443-Processor25] (JDBCTransaction.java:163) - rolled back JDBC Connection
[2009-10-23 14:33:07,637] DEBUG [http-8443-Processor25] (JDBCContext.java:207) - after transaction completion
[2009-10-23 14:33:07,637] DEBUG [http-8443-Processor25] (ConnectionManager.java:296) - aggressively releasing JDBC connection
[2009-10-23 14:33:07,637] DEBUG [http-8443-Processor25] (ConnectionManager.java:333) - closing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
[2009-10-23 14:33:07,637] DEBUG [http-8443-Processor25] (DriverManagerConnectionProvider.java:129) - returning connection to pool, pool size: 1
[2009-10-23 14:33:07,637] DEBUG [http-8443-Processor25] (SessionImpl.java:434) - after transaction completion
[2009-10-23 14:33:07,637] DEBUG [http-8443-Processor25] (SessionImpl.java:368) - automatically closing session
[2009-10-23 14:33:07,637] DEBUG [http-8443-Processor25] (SessionImpl.java:296) - closing session
[2009-10-23 14:33:07,637] DEBUG [http-8443-Processor25] (ConnectionManager.java:267) - connection already null in cleanup : no action
[2009-10-23 14:33:07,637] ERROR [http-8443-Processor25] (PersistableDAOImpl.java:87) - makePersistent(Camera)
org.hibernate.exception.ConstraintViolationException: could not insert collection: [x.y.z.Camera.alarmZones#641]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:69)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1058)
at org.hibernate.action.CollectionUpdateAction.execute(CollectionUpdateAction.java:51)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:243)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:227)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:143)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:296)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:980)
at sun.reflect.GeneratedMethodAccessor56.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:292)
at $Proxy25.flush(Unknown Source)
at com.silkspeed.ssparts.server.PersistableDAOImpl.makePersistent(PersistableDAOImpl.java:82)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:292)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:155)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:122)
at org.springframework.remoting.support.RemoteInvocationTraceInterceptor.invoke(RemoteInvocationTraceInterceptor.java:68)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:144)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:174)
at $Proxy38.makePersistent(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.remoting.support.RemoteInvocation.invoke(RemoteInvocation.java:179)
at org.springframework.remoting.support.DefaultRemoteInvocationExecutor.invoke(DefaultRemoteInvocationExecutor.java:33)
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invoke(RemoteInvocationBasedExporter.java:76)
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invokeAndCreateResult(RemoteInvocationBasedExporter.java:112)
at org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter.handleRequest(HttpInvokerServiceExporter.java:80)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:44)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:684)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:625)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:392)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:357)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at x.y.z.server.SessionInfo.doFilter(SessionInfo.java:91)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:525)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:151)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:874)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.sql.SQLException: Attempt to insert null into a non-nullable column: column: ALARMZONES table: CAMERAALARMZONES in statement [insert into cameraalarmzones (cameras_id, elt) values (?, ?)]
at org.hsqldb.jdbc.Util.throwError(Unknown Source)
at org.hsqldb.jdbc.jdbcPreparedStatement.executeUpdate(Unknown Source)
at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:23)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1039)
... 58 more
Here's my hibernate config file:
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:file:dbfilename;shutdown=true</property>
<property name="connection.username">*************</property>
<property name="connection.password">*************</property>
<property name="connection.autocommit">true</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<property name="hibernate.jdbc.batch_size">0</property>
<property name="hibernate.jdbc.fetch_size">0</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.silkspeed.sightlogix.cs.AlarmZone"/>
<mapping class="com.silkspeed.sightlogix.cs.Camera" />
<mapping class="com.silkspeed.sightlogix.cs.Zone"/>
...
Thanks in advance.
There are several problems with your code:
You have ids declared as Serializable instead of plain long (or Long). Why?
You should map actual Zone (or AlarmZone if you want) instances in your OneToMany relationship instead of ids. There's no need for intermediate table unless the relationship is really ManyToMany in which case it should be mapped as such (can a single AlarmZone belong to more than one Camera? If so, it's many-to-many).
You have inheritance annotation on your Camera entity. Why? Is it part of another hierarchy?
The "boilerplate" code you're using is bad. Transaction should enclose an entire unit of work, not individual entity. Explicit flushing is unnecessary.
Sample mapping:
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
#Table(name = "cameras")
public class Camera {
private long id;
private List<AlarmZone> alarm_zones = new ArrayList<AlarmZone>();
#SequenceGenerator(name="Camera_Gen", sequenceName="cameras_seq")
#Id #GeneratedValue(generator="Camera_Gen")
public long getId() {
return this.id;
}
#OneToMany(mappedBy="camera") // this maps a bi-directional relationship
public List<AlarmZone> getAlarmZones() {
return alarm_zones;
}
...
}
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
#Table(name = "zones")
public class Zone {
// same deal as above
...
}
#Entity
#Table(name = "alarmzones")
public class AlarmZone extends Zone {
private Camera camera;
#ManyToOne
public Camera getCamera() {
return this.camera;
}
}
Details on identifier mapping and association mapping.

Categories