Hibernate ConstraintViolationException in join table - java

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.

Related

Saving entities with Hibernate 5.1 and Spring 5.2.9 fails to save entity (spring-boot 2.3.4, spring-boot-devtools) [duplicate]

This question already has an answer here:
Classes loaded by different Classloaders in Spring Boot and Logback
(1 answer)
Closed 2 years ago.
[Edit: fixed spring version in q to 5.2.9. v2.3.4 is the aggregated maven dep.]
I've gone through heaps of posts to try to figure this out. Seems like there's a huge compatibility issue, but I can't figure out which versions to change to. I don't do Java normally, but have to when teaching, so hoping someone will ignore my non-existant Java-skills and bless me with some advice. 🤷‍♂️🙏
If I step through disassembled code, I can see that my unit tests (integrated) does something else when trying to reflect my ID property than what is done when ran with Spring.
[Edit] Here's the SQL log:
Hibernate: create table ChatMessages (Id varchar(255) not null, UserName varchar(50), Message varchar(512), primary key (Id))
2020-10-07 10:01:15.142 INFO 43304 --- [nio-8081-exec-8] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select chatmessag0_.Id as Id1_0_, chatmessag0_.UserName as UserName2_0_, chatmessag0_.Message as Message3_0_ from ChatMessages chatmessag0_
Here's the exception and the top of the trace:
[nio-8081-exec-6] o.h.p.access.spi.GetterMethodImpl : HHH000122: IllegalArgumentException in class: org.hiof.chatroom.core.ChatMessage, getter method of property: id
2020-10-07 02:28:59.438 ERROR 47504 --- [nio-8081-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of org.hiof.chatroom.core.ChatMessage.id] with root cause
java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_172]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_172]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_172]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_172]
at org.hibernate.property.access.spi.GetterMethodImpl.get(GetterMethodImpl.java:41) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:223) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4633) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.id.Assigned.generate(Assigned.java:32) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669) ~[hibernate-core-5.1.0.Final.jar:5.1.0.Final]
at org.hiof.chatroom.database.ChatMessageRepository.add(ChatMessageRepository.java:21) ~[classes/:na]
It's a super simple DB setup with SQL Lite.
The only entity is mapped as such:
<class name="org.hiof.chatroom.core.ChatMessage" table="ChatMessages">
<id name="id" column="Id">
<generator class="assigned"/>
</id>
<property name="user" column="UserName" length="50"/>
<property name="message" column="Message" length="512"/>
</class>
And the entity:
public class ChatMessage {
private String id;
private String user;
private String message;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Here's a test that goes through with no different infrastructure and config than (not) having Spring running the application:
public class When_persisting_chat_messages {
#Test
public void stores_message() throws Exception {
DatabaseManager.ensureDatabase("./db/chat-test.db");
UnitOfWork uow = new UnitOfWork();
ChatMessageRepository repo = new ChatMessageRepository(uow);
ChatMessage msg = new ChatMessage();
String id = UUID.randomUUID().toString();
msg.setId(id);
repo.add(msg);
uow.saveChanges();
uow.close();
uow = new UnitOfWork();
repo = new ChatMessageRepository(uow);
msg = repo.get(id);
Assertions.assertNotNull(msg);
}
}
I'm fairly sure it has to do with the StandardServiceRegistryBuilder involved in setting up the session factory in my UOW. No idea what to do tho.
It's way too late and I was hoping to demo this for some students tomorrow, so I apologize if I left this post a bit off the prefered standards of SO.
[Edit]
Repo is published here: https://github.com/lars-erik/hiof-sweat2020-chatroom-demo
[Edit after 2 days]
I managed to pin down the place it throws when ran in the web project. For a dotnet developer like me, this smells like two versions of my core "assembly" (module) is loaded into the "domain" and the ID property is read from the "wrong module's metadata". No idea tho, but that's how it seems. In the getIdentifier method, both owner and idGetter points to the same class, org.hiof.chatroom.core.ChatMessage. Yet the invoke insists the instance is not the id getter's declaring class. Here's the trace:
get:42, GetterMethodImpl (org.hibernate.property.access.spi)
getIdentifier:230, AbstractEntityTuplizer (org.hibernate.tuple.entity)
getIdentifier:5155, AbstractEntityPersister (org.hibernate.persister.entity)
generate:31, Assigned (org.hibernate.id)
saveWithGeneratedId:115, AbstractSaveEventListener (org.hibernate.event.internal)
saveWithGeneratedOrRequestedId:194, DefaultSaveOrUpdateEventListener (org.hibernate.event.internal)
saveWithGeneratedOrRequestedId:38, DefaultSaveEventListener (org.hibernate.event.internal)
entityIsTransient:179, DefaultSaveOrUpdateEventListener (org.hibernate.event.internal)
performSaveOrUpdate:32, DefaultSaveEventListener (org.hibernate.event.internal)
onSaveOrUpdate:75, DefaultSaveOrUpdateEventListener (org.hibernate.event.internal)
accept:-1, 1659093435 (org.hibernate.internal.SessionImpl$$Lambda$541)
fireEventOnEachListener:102, EventListenerGroupImpl (org.hibernate.event.service.internal)
fireSave:636, SessionImpl (org.hibernate.internal)
save:629, SessionImpl (org.hibernate.internal)
save:624, SessionImpl (org.hibernate.internal)
[Edit oct. 11.]
Debugging currently shows two versions of the ChatMessage class when ran with spring. :/
owner.getClass() = {Class#9587} "class org.hiof.chatroom.core.ChatMessage"
owner.getClass() == getterMethod.getDeclaringClass() = false
org.hiof.chatroom.core.ChatMessage.class = {Class#8446} "class org.hiof.chatroom.core.ChatMessage"
getterMethod.getDeclaringClass() = {Class#8446} "class org.hiof.chatroom.core.ChatMessage"
The owner's class' classloader is "RestartClassLoader", while the declaring one is "Launcher$AppClassLoader".
This was caused by spring-boot-devtools. It creates a classloader called RestartClassLoader to speed up restarts. However, it messes with Hibernate's metadata reflection giving two instances of the same type when we get to id reflection.
So this ends up being somewhat of a dupe of this and a few others:
Classes loaded by different Classloaders in Spring Boot and Logback

Spring data JPA repository delete query getting fired after returning from service

I am using spring data jpa in my spring boot application.
Below is my SchoolService method to delete school by school id.
#Override
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public boolean deleteSchool(Long id) {
log.debug("Deleting school entry with the school id: {}", id);
try {
schoolRepository.delete(id);
return true;
} catch(Exception e){
log.error(e.toString());
return false;
}
}
and my SchoolRepository is as follows.
public interface SchoolRepository<School, Long> extends PagingAndSortingRepository<School, Long> {
}
When there is some exception while deleting a school, this service method should throw an exception which should be caught and false should be returned indicating that the delete operation has failed.
But here in above case, it returns true and then it throws an exception. Not sure why?
Below is the stacktrace
2016-07-27 16:13:30.809 DEBUG 7650 --- [nio-8080-exec-6] c.sts.app.core.common.aop.LoggingAspect : Enter: com.sts.app.school.service.SchoolService.deleteSchool() with argument[s] = [1]
2016-07-27 16:13:30.809 DEBUG 7650 --- [nio-8080-exec-6] c.s.a.s.service.impl.SchoolServiceImpl : Deleting school entry with the school id: 1
Hibernate:
select
school0_.id as id1_4_0_,
school0_.created_by as created_2_4_0_,
school0_.created_date as created_3_4_0_,
school0_.last_modified_by as last_mod4_4_0_,
school0_.last_modified_date as last_mod5_4_0_,
school0_.address as address6_4_0_,
school0_.name as name7_4_0_
from
schools school0_
where
school0_.id=?
2016-07-27 16:13:30.812 DEBUG 7650 --- [nio-8080-exec-6] c.sts.app.core.common.aop.LoggingAspect : Exit: com.sts.app.school.service.SchoolService.deleteSchool() with result = true
Hibernate:
delete
from
schools
where
id=?
2016-07-27 16:13:30.815 WARN 7650 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1451, SQLState: 23000
2016-07-27 16:13:30.815 ERROR 7650 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : Cannot delete or update a parent row: a foreign key constraint fails (`blank_app`.`students`, CONSTRAINT `FK_d8qlrs5j411ofxq8uy2nlhxm` FOREIGN KEY (`school_id`) REFERENCES `schools` (`id`))
2016-07-27 16:13:30.816 WARN 7650 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 1451, SQLState: 23000
2016-07-27 16:13:30.816 WARN 7650 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : Cannot delete or update a parent row: a foreign key constraint fails (`blank_app`.`students`, CONSTRAINT `FK_d8qlrs5j411ofxq8uy2nlhxm` FOREIGN KEY (`school_id`) REFERENCES `schools` (`id`))
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:259)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:225)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:485)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
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:208)
at com.sun.proxy.$Proxy126.deleteSchool(Unknown Source)
at com.sts.app.school.web.SchoolController.deleteSchool(SchoolController.java:71)
at com.sts.app.school.web.SchoolController$$FastClassByCGLIB$$a5f9e3ee.invoke(<generated>)

I'm getting ResourceException: Transaction is not active

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 ?

SQL Error: 17401, SQLState: 99999 Protocol violation: [6, 7, 0]

Looking for help with an intermittent error. Following extract is from the log file. Can't think what else to add but I will add more if needed.
13 Oct 2015 14:37:43,691 2746599 [pool-1-thread-1] INFO snbts.proteus.integrationengine.IntegrationThread - Processing batch: 16888445 on integration Queue 1
13 Oct 2015 14:37:46,831 2749739 [pool-1-thread-2] INFO snbts.proteus.integrationengine.IntegrationThread - Queue 2 is alive.
13 Oct 2015 14:37:52,706 2755614 [pool-1-thread-1] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 17401, SQLState: 99999
13 Oct 2015 14:37:52,706 2755614 [pool-1-thread-1] ERROR org.hibernate.util.JDBCExceptionReporter - Protocol violation: [6, 7, 0]
13 Oct 2015 14:37:52,706 2755614 [pool-1-thread-1] INFO org.hibernate.event.def.DefaultLoadEventListener - Error performing load command
org.hibernate.exception.GenericJDBCException: could not load an entity: [snbts.proteus.dataaccess.IntegrationQueue#2]
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1799)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:47)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:41)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:2730)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:365)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:346)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:123)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:82)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:862)
at org.hibernate.impl.SessionImpl.immediateLoad(SessionImpl.java:820)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:62)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:98)
at org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:158)
at snbts.proteus.dataaccess.IntegrationQueue$$EnhancerByCGLIB$$14c8fbf7.setStatus(<generated>)
at snbts.proteus.integrationengine.IntegrationThread.setStatus(IntegrationThread.java:109)
at snbts.proteus.integrationengine.IntegrationThread.run(IntegrationThread.java:48)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(Unknown Source)
at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.sql.SQLException: Protocol violation: [6, 7, 0]
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:464)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1044)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1199)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1289)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3584)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3628)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1493)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:139)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1669)
at org.hibernate.loader.Loader.doQuery(Loader.java:662)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1785)
... 24 more
13 Oct 2015 14:37:52,706 2755614 [pool-1-thread-1] ERROR snbts.proteus.integrationengine.IntegrationThread - Problem updating database: could not load an entity: [snbts.proteus.dataaccess.IntegrationQueue#2]
13 Oct 2015 14:37:54,752 2757660 [pool-1-thread-1] WARN com.mchange.v2.c3p0.impl.NewPooledConnection - [c3p0] A PooledConnection that has already signalled a Connection error is still in use!
13 Oct 2015 14:37:54,752 2757660 [pool-1-thread-1] WARN com.mchange.v2.c3p0.impl.NewPooledConnection - [c3p0] Another error has occurred [ java.sql.SQLException: Protocol violation ] which will not be reported to listeners!
java.sql.SQLException: Protocol violation
at oracle.jdbc.driver.T4CTTIiov.unmarshalV10(T4CTTIiov.java:210)
at oracle.jdbc.driver.T4C8Oall.readIOV(T4C8Oall.java:592)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:325)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:884)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1167)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1289)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3584)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3628)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1493)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:139)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1669)
at org.hibernate.loader.Loader.doQuery(Loader.java:662)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1785)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:47)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:41)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:2730)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:365)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:346)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:123)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:82)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:862)
at org.hibernate.impl.SessionImpl.immediateLoad(SessionImpl.java:820)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:62)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:98)
at org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:158)
at snbts.proteus.dataaccess.IntegrationQueue$$EnhancerByCGLIB$$14c8fbf7.toString(<generated>)
at java.util.Formatter$FormatSpecifier.printString(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.lang.String.format(Unknown Source)
at snbts.proteus.integrationengine.queue.QueueItem.build(QueueItem.java:72)
at snbts.proteus.integrationengine.IntegrationThread.processIntegrationQueue(IntegrationThread.java:58)
at snbts.proteus.integrationengine.IntegrationThread.run(IntegrationThread.java:49)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(Unknown Source)
at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Versions we are using:
Java 6
Hibernate 3.1.3
ojdbc6 11.2.0.4.0
Oracle 10g EE 10.2.0.5.0 64bit
Method attempting to load the entity:
private boolean setStatus(final String status) {
LOGGER.trace(String.format("Setting status to: %s on %s", status, integrationQueue.getDescription()));
boolean hasDbConnection = true;
try {
final Session session = CustomSessionFactory.getSessionFactory().getSession();
session.beginTransaction();
LOGGER.trace(CustomSessionFactory.TRANSACTION_BEGUN);
this.integrationQueue = (IntegrationQueue)session.load(IntegrationQueue.class, integrationQueue.getId());
integrationQueue.setStatus(status);
session.update(integrationQueue);
session.flush();
LOGGER.trace(String.format("Session Object Update: Integration Queue %d", integrationQueue.getId()));
session.getTransaction().commit();
LOGGER.trace(CustomSessionFactory.TRANSACTION_COMMITTED);
LOGGER.trace(String.format("Status set to: %s on %s", status, integrationQueue.getDescription()));
} catch (org.hibernate.exception.JDBCConnectionException e) {
LOGGER.error(String.format("Database Connection Problem: %s", e.getMessage()));
CustomSessionFactory.getSessionFactory().removeSession();
hasDbConnection = false;
} catch (GenericJDBCException e) {
LOGGER.error(String.format("Problem updating database: %s", e.getMessage()));
}
return hasDbConnection;
Entity:
public class IntegrationQueue implements Serializable {
public static final String STATUS_SHUTDOWN = "Shutdown";
public static final String STATUS_ACTIVE = "Active";
public static final String STATUS_IDLE = "Idle";
public static final String STATUS_ERROR_WC = "Error - Wrong Configuration";
private long id;
private String description;
private String status;
private IntegrationEngine integrationEngine;
public IntegrationQueue() {
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
public IntegrationEngine getIntegrationEngine() {
return integrationEngine;
}
public void setIntegrationEngine(final IntegrationEngine integrationEngine) {
this.integrationEngine = integrationEngine;
}
public String getStatus() {
return status;
}
public void setStatus(final String status) {
this.status = status;
}
public String toString(){
return String.format("Integration Queue: %d - %s", id, status);
}
}
HBM File:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="snbts.proteus.dataaccess.IntegrationQueue" table="INTEGRATIONQUEUE">
<id name="id" type="long" column="INTEGRATIONQUEUE_ID">
<generator class="assigned"/>
</id>
<property name="description" type="string" column="DESCRIPTION">
<meta attribute="field-description">
The description of the record.
</meta>
</property>
<property name="status" type="string" column="STATUS">
<meta attribute="field-description">
The status of the record.
</meta>
</property>
<many-to-one name="integrationEngine" class="snbts.proteus.dataaccess.IntegrationEngine"
column="INTEGRATIONENGINE_ID" not-null="true"/>
</class>
</hibernate-mapping>

Hibernate throws SQLException "id field does not have a default value"

In a spring mvc app using hibernate, I am encountering the following error when i try to persist an entity:
java.sql.SQLException: Field 'thirdIds_huid' doesn't have a default value
The database schema is generated by hbm2ddl. How can I change the hibernate code so that these entities can be persisted successfully?
The two entities are AClass and HClass. The code for AClass is::
import javax.persistence.*;
#Entity(name = "AClass")
#Table(name = "a_class")
public class AClass {
private Long auid;
private HClass firstId;
private List<HClass> secondIds;
private List<HClass> thirdIds;
#Id
#Column(name = "auid")
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getAuid(){return auid;}
public void setAuid(Long hid){auid = hid;}
#ManyToOne
public HClass getFirstId(){return firstId;}
public void setFirstId(HClass tid){firstId = tid;}
#OneToMany
public List<HClass> getSecondIds(){return secondIds;}
public void setSecondIds(List<HClass> tid){secondIds = tid;}
#OneToMany
public List<HClass> getThirdIds(){return thirdIds;}
public void setThirdIds(List<HClass> i){thirdIds = i;}
}
The code for HClass is:
import javax.persistence.*;
#Entity(name = "HClass")
#Table(name = "h_class")
public class HClass {
private Long huid;
private String somefield;
#Id
#Column(name = "huid")
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getHuid(){return huid;}
public void setHuid(Long hid){huid = hid;}
#Column(name = "somefield")
public String getSomefield(){return somefield;}
public void setSomefield(String rt){somefield = rt;}
}
The controller code that triggers the error is:
#RequestMapping(value = "/TriggerTheError", method = RequestMethod.GET)
public String processFindForm( HttpServletRequest request, Map<String, Object> model) {
AClass ac = new AClass();
HClass hc = new HClass();
hc.setSomefield("some value goes here");
List<HClass> hcs = new ArrayList<HClass>();
hcs.add(hc);
ac.setSecondIds(hcs);
HClass hc2 = new HClass();
hc2.setSomefield("another value goes here");
List<HClass> hcs2 = new ArrayList<HClass>();
hcs2.add(hc2);
ac.setThirdIds(hcs2);
persistAClass(ac);
return "ReproduceError";
}
public void persistAClass(AClass ac){
if(ac.getThirdIds()!=null){
if(ac.getThirdIds().size()==0){ac.setThirdIds(null);System.out.println("thirdids re-set to null.");}
if(ac.getThirdIds()!=null){
System.out.println("thirdids!=null: size is: "+ac.getThirdIds().size());
for(int dd = 0;dd<ac.getThirdIds().size();dd++){
this.serviceLayer.saveHClass(ac.getThirdIds().get(dd));
}
}
}
if(ac.getSecondIds()!=null){
if(ac.getSecondIds().size()==0){ac.setSecondIds(null);System.out.println("secondids re-set to null.");}
if(ac.getSecondIds()!=null){
System.out.println("secondsid!=null: size is:"+ac.getSecondIds().size());
for(int kk = 0;kk < ac.getSecondIds().size();kk++){
this.serviceLayer.saveHClass(ac.getSecondIds().get(kk));
}
}
}
if(ac.getFirstId()!=null){
System.out.println("firstid!=null: huid value is: "+ac.getFirstId().getHuid());
this.serviceLayer.saveHClass(ac.getFirstId());
}
System.out.println("-------------------- data follows ------------------------------");
for(int a=0;a<ac.getSecondIds().size();a++){
System.out.println("a, secondids somefield are: "+a+", "+ac.getSecondIds().get(a).getSomefield());
}
if(ac.getFirstId()!=null){
String rt = "";
if(ac.getFirstId().getSomefield()!=null){rt = ac.getFirstId().getSomefield();}
System.out.println("first id some field is: "+rt);
}
if(ac.getThirdIds()!=null){
for(int b = 0;b<ac.getThirdIds().size();b++){
String sf = "";
if(ac.getThirdIds().get(b).getSomefield()!=null){sf = ac.getThirdIds().get(b).getSomefield();}
System.out.println("b, third ids somefield are: "+b+", "+sf);
}
}
System.out.println("-------------------- end of data -------------------------------");
this.serviceLayer.saveAClass(ac);
}
Note that the line of code in the controller above that triggers the error is:
this.serviceLayer.saveAClass(ac);
The repository code finally called by the service layer is:
#Override
public void saveAClass(AClass myac) throws DataAccessException{
if (myac.getAuid() == null) {this.em.persist(myac);}
else {this.em.merge(myac);}
}
The complete stack trace is:
11:51:04.334 [http-nio-8080-exec-3] DEBUG o.s.web.servlet.DispatcherServlet - Handler execution resulted in exception - forwarding to resolved error view: ModelAndView: reference to view with name 'exception'; model is {exception=org.springframework.orm.hibernate3.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException for SQL [n/a]; SQL state [HY000]; error code [1364]; could not execute statement; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement}
org.springframework.orm.hibernate3.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException for SQL [n/a]; SQL state [HY000]; error code [1364]; could not execute statement; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:651) ~[spring-orm-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:106) ~[spring-orm-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517) ~[spring-orm-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:755) ~[spring-tx-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:724) ~[spring-tx-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:475) ~[spring-tx-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:270) ~[spring-tx-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94) ~[spring-tx-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) ~[spring-aop-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) ~[spring-aop-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at com.sun.proxy.$Proxy27.saveAClass(Unknown Source) ~[na:na]
at example.controller.SomeModelClassController.persistAClass(SomeModelClassController.java:96) ~[SomeModelClassController.class:na]
at example.controller.SomeModelClassController.processFindForm(SomeModelClassController.java:50) ~[SomeModelClassController.class:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_79]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_79]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_79]
at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_79]
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) ~[spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) ~[spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) ~[spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) ~[spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) ~[spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618) [servlet-api.jar:na]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725) [servlet-api.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) [catalina.jar:8.0.15]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.15]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.15]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.15]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-websocket.jar:8.0.15]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.15]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.15]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.15]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.15]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) [catalina.jar:8.0.15]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) [catalina.jar:8.0.15]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) [catalina.jar:8.0.15]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) [catalina.jar:8.0.15]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [catalina.jar:8.0.15]
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610) [catalina.jar:8.0.15]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [catalina.jar:8.0.15]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537) [catalina.jar:8.0.15]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085) [tomcat-coyote.jar:8.0.15]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658) [tomcat-coyote.jar:8.0.15]
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222) [tomcat-coyote.jar:8.0.15]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556) [tomcat-coyote.jar:8.0.15]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513) [tomcat-coyote.jar:8.0.15]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_79]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_79]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:8.0.15]
at java.lang.Thread.run(Thread.java:745) [na:1.7.0_79]
Caused by: org.hibernate.exception.GenericJDBCException: could not execute statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:136) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:58) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1256) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:58) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:364) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:356) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:281) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:328) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1234) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:75) ~[hibernate-entitymanager-4.2.1.Final.jar:4.2.1.Final]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:513) ~[spring-orm-3.2.5.RELEASE.jar:3.2.5.RELEASE]
... 57 common frames omitted
Caused by: java.sql.SQLException: Field 'thirdIds_huid' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078) ~[mysql-connector-java-5.1.27.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237) ~[mysql-connector-java-5.1.27.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169) ~[mysql-connector-java-5.1.27.jar:na]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617) ~[mysql-connector-java-5.1.27.jar:na]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778) ~[mysql-connector-java-5.1.27.jar:na]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2825) ~[mysql-connector-java-5.1.27.jar:na]
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2156) ~[mysql-connector-java-5.1.27.jar:na]
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2459) ~[mysql-connector-java-5.1.27.jar:na]
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2376) ~[mysql-connector-java-5.1.27.jar:na]
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2360) ~[mysql-connector-java-5.1.27.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
... 71 common frames omitted
11:51:04.336 [http-nio-8080-exec-3] DEBUG o.s.w.s.v.ContentNegotiatingViewResolver - Requested media types are [text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8] based on Accept header types and producible media types [*/*])
11:51:04.336 [http-nio-8080-exec-3] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'exception'
11:51:04.337 [http-nio-8080-exec-3] DEBUG o.s.w.s.v.ContentNegotiatingViewResolver - Returning [org.springframework.web.servlet.view.JstlView: name 'exception'; URL [/WEB-INF/jsp/exception.jsp]] based on requested media type 'text/html'
11:51:04.337 [http-nio-8080-exec-3] DEBUG o.s.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'exception'; URL [/WEB-INF/jsp/exception.jsp]] in DispatcherServlet with name 'MinimalDbaseExample'
11:51:04.337 [http-nio-8080-exec-3] DEBUG o.s.web.servlet.view.JstlView - Added model object 'exception' of type [org.springframework.orm.hibernate3.HibernateJdbcException] to request in view with name 'exception'
11:51:04.337 [http-nio-8080-exec-3] DEBUG o.s.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/jsp/exception.jsp] in InternalResourceView 'exception'
11:51:04.380 [http-nio-8080-exec-3] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request
ANSWER
The solution came from the part of #VladMihalcea's answer that involved removing the multiple references to HClass in the list of properties of AClass. Specifically, I created types HClassFirst, HClassSecond, and HClassThird, all with the same properties and methods. This way, hibernate did not get confused by multiple properties of AClass linking to the same type. The app's architecture allows for this. I decided against using inheritance because there are already a lot of links in each table, and I don't want to bump into other errors related to an excess number of foreign keys.
Thus, the solution was not in hibernate annotations. Instead, the solution was in adjusting the model that hibernate is being asked to persist.
I think it's much simpler to use cascading in this example:
#Entity(name = "AClass")
#Table(name = "a_class")
public class AClass {
private Long auid;
private HClass firstId;
private List<HClass> secondIds = new ArrayList<>();
private List<HClass> thirdIds = new ArrayList<>();
#Id
#Column(name = "auid")
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getAuid(){return auid;}
public void setAuid(Long hid){auid = hid;}
#ManyToOne
public HClass getFirstId(){return firstId;}
public void setFirstId(HClass tid){firstId = tid;}
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
public List<HClass> getSecondIds(){return secondIds;}
public void setSecondIds(List<HClass> tid){secondIds = tid;}
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
public List<HClass> getThirdIds(){return thirdIds;}
public void setThirdIds(List<HClass> i){thirdIds = i;}
}
Then the persisting logic becomes just that:
public void persistAClass(AClass ac){
this.serviceLayer.saveAClass(ac);
}
The original issue might be due to this:
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:58) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
This is how you should initialize collections in your entities:
private List<HClass> secondIds = new ArrayList<>();
private List<HClass> thirdIds = new ArrayList<>();
So, when you want to modify the collections, you don't reset them, but rather rely on the dirty checking mechanism to add/remove elements:
AClass ac = new AClass();
HClass hc = new HClass();
hc.setSomefield("some value goes here");
ac.getSecondIds().add(hc);
HClass hc2 = new HClass();
hc2.setSomefield("another value goes here");
ac.getThirdIds().add(hc2);
persistAClass(ac);
During a merge, you should remove the children that no longer belong to a parent and add the new ones coming from your web request.
Edit
I tried your example on my local machine and like the problem is the way you do the mappings. Because you link the Aclass with HClass on 3 different relations (one many-to-one and 2 one-to-many), this is what you get:
create table a_class (auid bigint generated by default as identity (start with 1), firstId_huid bigint, primary key (auid))
create table a_class_h_class (a_class_auid bigint not null, thirdIds_huid bigint not null, secondIds_huid bigint not null)
create table h_class (huid bigint generated by default as identity (start with 1), somefield varchar(255), primary key (huid))
alter table a_class_h_class add constraint UK_qtt8gi008ssnfi4t3mo3tq310 unique (thirdIds_huid)
alter table a_class_h_class add constraint UK_35k583bmbiomo0rc6t74ba41g unique (secondIds_huid)
alter table a_class add constraint FK_1hw1d6sy2yhp9hirqgb6rx6yr foreign key (firstId_huid) references h_class
alter table a_class_h_class add constraint FK_qtt8gi008ssnfi4t3mo3tq310 foreign key (thirdIds_huid) references h_class
alter table a_class_h_class add constraint FK_jng9ogc4rmlmojd31weygk6l9 foreign key (a_class_auid) references a_class
alter table a_class_h_class add constraint FK_35k583bmbiomo0rc6t74ba41g foreign key (secondIds_huid) references h_class
So when you try to enter an entity:
Query:{[insert into a_class (auid, firstId_huid) values (default, ?)][-5]}
Query:{[insert into h_class (huid, somefield) values (default, ?)][some value goes here]}
Query:{[insert into h_class (huid, somefield) values (default, ?)][another value goes here]}
Query:{[insert into a_class_h_class (a_class_auid, secondIds_huid) values (?, ?)][1,1]}
WARN [Alice]: o.h.e.j.s.SqlExceptionHelper - SQL Error: -10, SQLState: 23502
ERROR [Alice]: o.h.e.j.s.SqlExceptionHelper - integrity constraint violation: NOT NULL check constraint; SYS_CT_10096 table: A_CLASS_H_CLASS column: THIRDIDS_HUID
The only fix is to change the Mapping. Instead of 3 HClass associations you should have something else, maybe an inheritance model or something. Always try to model your domain entities on a valid schema.
the "persist detached entity error" is because new transaction is opened for each persist action. For new opened transaction, the entity persisted(the HCClass) in last transaction become "detached".
I suggest you group all you persist action in one transaction, you can do it by move persistAClass to service layer and annotate it #Transactional.

Categories