Internal Exception: java.sql.SQLSyntaxErrorException: ORA-00972: identifier is too long - jpa

i develop an application with swing
i habe a database with few tables; these Tables are connected with foreign key
When I try to run this application , i have the error;
Exception in thread "AWT-EventQueue-0" javax.ejb.EJBException: EJB Exception: ; nested exception is:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.4.2.v20130514-5956486): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: ORA-00972: Bezeichner ist zu lang
Error Code: 972
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.unwrapRemoteException(RemoteBusinessIntfProxy.java:117)
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.invoke(RemoteBusinessIntfProxy.java:92)
at com.sun.proxy.$Proxy0.getKinokindergeldfallFindAll(Unknown Source)
at de.itech.kiwi.startseite.actionPerformed(startseite.java:242)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:702)
at java.awt.EventQueue$4.run(EventQueue.java:700)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.4.2.v20130514-5956486): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: ORA-00972: Bezeichner ist zu lang
Error Code: 972
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:333)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:646)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:537)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1805)
at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:566)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:207)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:193)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.selectOneRow(DatasourceCallQueryMechanism.java:668)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectOneRowFromTable(ExpressionQueryMechanism.java:2769)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectOneRow(ExpressionQueryMechanism.java:2722)
at org.eclipse.persistence.queries.ReadObjectQuery.executeObjectLevelReadQuery(ReadObjectQuery.java:453)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1150)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:852)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1109)
at org.eclipse.persistence.queries.ReadObjectQuery.execute(ReadObjectQuery.java:421)
at org.eclipse.persistence.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:2977)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1607)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1589)
at org.eclipse.persistence.internal.indirection.NoIndirectionPolicy.valueFromQuery(NoIndirectionPolicy.java:326)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRowInternal(ForeignReferenceMapping.java:2162)
at org.eclipse.persistence.mappings.OneToOneMapping.valueFromRowInternal(OneToOneMapping.java:1717)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java:2051)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.readFromRowIntoObject(ForeignReferenceMapping.java:1386)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:448)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:814)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneNormally(ObjectBuilder.java:723)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:676)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:609)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:564)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:777)
at org.eclipse.persistence.queries.ReadAllQuery.registerResultInUnitOfWork(ReadAllQuery.java:797)
at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:434)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1150)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:852)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1109)
at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:393)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1197)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2879)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1607)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1589)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1554)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:231)
at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:411)
at weblogic.persistence.QueryProxyImpl.getResultList(QueryProxyImpl.java:145)
at de.itech.kino.model.ItechSessionEJBBean.getKinokindergeldfallFindAll(ItechSessionEJBBean.java:167)
at de.itech.kino.model.ItechSessionEJB_ohevbk_ItechSessionEJBImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionRemoteMethodInvoker.invoke(SessionRemoteMethodInvoker.java:34)
at de.itech.kino.model.ItechSessionEJB_ohevbk_ItechSessionEJBImpl.getKinokindergeldfallFindAll(Unknown Source)
at de.itech.kino.model.ItechSessionEJB_ohevbk_ItechSessionEJBImpl_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:693)
at weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:230)
at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:519)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:515)
at weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:295)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:254)
This table Kinokindergeldfall hat a foreign key in the table kinoantragsteller
#OneToOne (cascade = CascadeType.ALL , fetch= FetchType.EAGER)
private Kinokindergeldfall kinokindergeldfall;
et the class kinokindergeldfall:
#Column(nullable= false )
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Kinokindergeldfall_Id_Seq_Gen")
private BigDecimal kindergeldfallid;
#Column(nullable = false)
private String kindergeldnummer;
#OneToOne(mappedBy = "kinokindergeldfall", cascade = CascadeType.ALL )
private Kinoantragsteller kinoantragstellerList;

If you don't supply #JoinColumn with a column name for some relation, JPA will assume the default one. The default one is constructed like <source_class_field_name>_<target_class_id_field_name> which in your case resolves to kinokindergeldfall_kindergeldfallid which is over 30 characters long. That's what causes the exception.
Since you wouldn't be able to create a column with this name in the first place, just add #JoinColumn(name = "<column name>") with the actual name of the column used as foreign key to another table (shorter than 30 characters).
#OneToOne (cascade = CascadeType.ALL , fetch= FetchType.EAGER)
#JoinColumn(name = "<column name>")
private Kinokindergeldfall kinokindergeldfall;

Related

Saving an entity when its child entity is initialized by one of its unique fields throws org.springframework.dao.InvalidDataAccessApiUsageException

Consider the two classes below:
class TerminalMaintenance{
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_MAINTENANCE")
#SequenceGenerator(name ="SEQ_MAINTENANCE", sequenceName = "SEQ_MAINTENANCE", allocationSize = 1)
private long id;
#Column(name="code", unique = true)
private String code;
#ManyToOne(fetch = FetchType.LAZY)
private Terminal terminal;
public TerminalMaintenance() {
}
public TerminalMaintenance(long id) {
this.id = id;
}
public TerminalMaintenance(String code) {
this.code = code;
}
...
}
class Terminal{
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_TERMINAL")
#SequenceGenerator(name ="SEQ_TERMINAL", sequenceName = "SEQ_TERMINAL", allocationSize = 1)
private long id;
#Column(name="code", unique = true)
private String code;
#OneToMany(
fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
orphanRemoval = true,
mappedBy = "terminal")
private List<TerminalMaintenance> maintenances;
...
}
interface TerminalRepo extends JpaRepository<Terminal, Long>{
}
interface TerminalMaintenanceRepo extends JpaRepository<TerminalMaintenance, Long>{
}
When I want to save the TerminalMaintenance entity, I already know id of its Terminal entity and I do not load its entire terminal object in order to persist object TerminalMaintenance like:
TerminalMaintenance terminalMaintenance = new TerminalMaintenance();
Terminal terminal = new Terminal(1); \\ using id constructor
terminalMaintenance.setTerminal(terminal);
terminalMaintenanceRepo.save(terminalMaintenance);
And it works fine. But when I want to instantiate the object Terminal using its code field - which is unique - like :
TerminalMaintenance terminalMaintenance = new TerminalMaintenance();
Terminal terminal = new Terminal("core123"); \\ using code constructor
terminalMaintenance.setTerminal(terminal);
terminalMaintenanceRepo.save(terminalMaintenance);
it thorws :
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : ir.noorbank.entity.tms.TerminalMaintenance.terminal -> ir.noorbank.entity.tms.Terminal; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : ir.noorbank.entity.tms.TerminalMaintenance.terminal -> ir.noorbank.entity.tms.Terminal
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:371)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:257)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:154)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy122.findAll(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:205)
at com.sun.proxy.$Proxy111.findAll(Unknown Source)
at ir.noorbank.repo.TerminalMaintenanceRepositoryTest.test(TerminalMaintenanceRepositoryTest.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:171)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:167)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:114)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:59)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : ir.noorbank.entity.tms.TerminalMaintenance.terminal -> ir.noorbank.entity.tms.Terminal
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:151)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1542)
at org.hibernate.query.Query.getResultList(Query.java:165)
at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:76)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:355)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:78)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.data.repository.core.support.ImplementationInvocationMetadata.invoke(ImplementationInvocationMetadata.java:72)
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:382)
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:205)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:549)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:155)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
... 66 more
Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : ir.noorbank.entity.tms.TerminalMaintenance.terminal -> ir.noorbank.entity.tms.Terminal
at org.hibernate.engine.spi.CascadingActions$8.noCascade(CascadingActions.java:379)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:167)
at org.hibernate.event.internal.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:158)
at org.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:148)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:81)
at org.hibernate.event.internal.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:50)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at org.hibernate.internal.SessionImpl.autoFlushIfRequired(SessionImpl.java:1328)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1408)
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1565)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1533)
... 88 more
I also tried #NaturalId above code property of Terminal but there is no change.
So, Is there a way to persist an entity by initializing its sub-entity using one of its unique properties instead of initializing it by id property?
p.s: Terminal with id == 1 and code == code123 is already persisted in the database.
This code:
TerminalMaintenance terminalMaintenance = new TerminalMaintenance();
Terminal terminal = new Terminal(1); \\ using id constructor
terminalMaintenance.setTerminal(terminal);
terminalMaintenanceRepo.save(terminalMaintenance);
works in Hibernate because the Terminal object contains the identifier and, unlike JPA, Hibernate can work just fine if the parent entity is represented by a POJO that has the id set.
On the other hand, this code:
TerminalMaintenance terminalMaintenance = new TerminalMaintenance();
Terminal terminal = new Terminal("core123"); \\ using code constructor
terminalMaintenance.setTerminal(terminal);
terminalMaintenanceRepo.save(terminalMaintenance);
doesn't work because the Terminal object reference doesn't have the id set, so there's no way for Hibernate to know what value to set for the associated FK column.
It won't work. TBH I'm genuinely surprised that the attempt with new Terminal(1) works.
You need to fetch the existing entity (terminalRepository.findByCode("123")) and use the result. Otherwise, as far as JPA is concerned, new Terminal("core123") is a brand new entity.

problem with postgresql sequence and hibernate

I often read this site, but this is the first time I write, hope I won't make mistakes and apologize for my bad english.
I get to the point: I have to develop code to insert records on a single table of a postgresql db, using hibernate on a Springboot project. The table has got a sequence, and I would like to use it to get the id's value.
Into the hbm.xml file of my table I have this:
table="td_tito">
<id name="idTito" column="ID_TITO">
<generator class="sequence">
<param name="sequence">seq_td_tito</param>
</generator>
</id>
<property ..../>
<property ..../>
In the bean class I have the variable idTito and its getter and setter methods.
When i try to save by calling save method of my class that implements JpaRepository interface, I get the following exception:
12:56:06.746 [main] DEBUG org.hibernate.engine.transaction.internal.TransactionImpl - On TransactionImpl creation, JpaCompliance#isJpaTransactionComplianceEnabled == false
12:56:06.747 [main] DEBUG org.hibernate.engine.transaction.internal.TransactionImpl - begin
12:56:06.756 [main] DEBUG org.hibernate.SQL - select nextval ('hibernate_sequence')
Hibernate: select nextval ('hibernate_sequence')
12:56:06.782 [main] DEBUG org.hibernate.engine.jdbc.spi.SqlExceptionHelper - could not extract ResultSet [n/a]
org.postgresql.util.PSQLException: ERROR: relation "hibernate_sequence" does not exist
Position: 17
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2510)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2245)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:311)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:447)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:368)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:159)
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:109)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57)
at org.hibernate.id.enhanced.SequenceStructure$1.getNextValue(SequenceStructure.java:95)
at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:523)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:115)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:179)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:75)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:626)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:619)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:614)
at com.xxx.hibernate.TestHIbernate.saveTdtito(TestHIbernate.java:122)
at com.xxx.hibernate.TestHIbernate.main(TestHIbernate.java:20)
12:56:06.782 [main] WARN org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 42P01
12:56:06.782 [main] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ERROR: relation "hibernate_sequence" does not exist
Position: 17
This is the Entity Class:
#Entity
public class TdTito {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long idTito;
private int lev;
...
public Long getIdTito() {
return idTito;
}
public void setIdTito(Long idTito) {
this.idTito = idTito;
}
public int getLev() {
return lev;
}
public void setLev(int lev) {
this.lev = lev;
}
}
By removing the annotations I get this error as I try to start the Application:
2020-06-16 15:26:46.394 ERROR 23244 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.xxx..entities.mappingdb.TdTito
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1108) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at com.xxx..Application.main(Application.java:14) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_241]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_241]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_241]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.2.5.RELEASE.jar:2.2.5.RELEASE]
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.xxx..entities.mappingdb.TdTito
at org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:266) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:211) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:781) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.processEntityHierarchies(AnnotationMetadataSourceProcessorImpl.java:254) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.processEntityHierarchies(MetadataBuildingProcess.java:230) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:273) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1202) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1233) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378) ~[spring-orm-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
... 21 common frames omitted
Any suggestion? Thank you so much to everybody
Step
If you are using you must remove all annotations from the entity
This line is causing the search for hibernate_sequence:
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Simply remove this line.
But I recommend to use use annotations. This will look like this:
#Id
#SequenceGenerator(name = "seq_td_tito", sequenceName = "seq_td_tito")
#GeneratedValue(generator = "seq_td_tito", strategy = GenerationType.SEQUENCE)
private Long idTito;
I struggled for sometime, then following combination worked, for the same strategy
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
my application.properties has these entries.
spring.datasource.username= postgres
spring.datasource.password= mypassword
spring.datasource.driver-class-name= org.postgresql.Driver
spring.jpa.generate-ddl= true
spring.jpa.hibernate.ddl-auto= update
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect
and pom.xml has one dependency as needed.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>

SpringData JPA Transaction management

please help me about Spring JPA Transaction Management
I have two methods: usersService.addUser and authoritiesService.addNew
#Service
#Transactional(propagation = PROPAGATION.SUPPORTS, readOnly=true)
public class UsersService {
#Autowired
UsersRepository usersRepository;
#Autowired
AuthotitiesRepository authoritiesReposotory;
#Transaction
public addUser(...){
usersRespository.addUser...
authoritiesRepository.addNew...
}
...
public interface UsersRepository extends JpaRepository<Users, String> {
#Transactional
#Modifying
#Query(value = "insert into users..."
}
public interface AuthoritiesRepository extends JpaRepository<Users, String> {
#Transactional
#Modifying
#Query(value = "insert into abc ...."
}
The problem is when authoritiesRepository.addNew throws Exception(by some SQL syntax) I want to automatically rollback user info.
How can I configure in repository, service ?
Here is the exception trace:
2019-05-22 08:33:16.185 WARN 2276 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 42102, SQLState: 42S02
2019-05-22 08:33:16.185 ERROR 2276 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : Table "AUTHORITIESS" not found; SQL statement:
insert into authoritiess(username, authority) values(?, ?) [42102-199]
2019-05-22 08:33:16.220 ERROR 2276 --- [nio-8080-exec-4] o.s.t.i.TransactionInterceptor : Application exception overridden by commit exception
com.springboot.example.exception.DbCRUDException: Error on add user
at com.springboot.example.security.service.UsersService.addUser(UsersService.java:141) ~[classes/:na]
at com.springboot.example.security.service.UsersService$$FastClassBySpringCGLIB$$3d37fb4e.invoke() ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) [spring-core-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749) [spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) [spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.17.jar:9.0.17]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_162]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_162]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.17.jar:9.0.17]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_162]
Caused by: com.springboot.example.exception.DbCRUDException: Error on add authority
at com.springboot.example.security.service.AuthoritiesService.addNew(AuthoritiesService.java:58) ~[classes/:na]
at com.springboot.example.security.service.UsersService.addUser(UsersService.java:139) ~[classes/:na]
... 114 common frames omitted
Caused by: org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [insert into authoritiess(username, authority) values(?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:279) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryExecution$ModifyingExecution.doExecute(JpaQueryExecution.java:256) ~[spring-data-jpa-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:91) ~[spring-data-jpa-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:136) ~[spring-data-jpa-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:125) ~[spring-data-jpa-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:605) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[sprin
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) [spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) [spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
... 134 common frames omitted
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "AUTHORITIESS" not found; SQL statement:
insert into authoritiess(username, authority) values(?, ?) [42102-199]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:451) ~[h2-1.4.199.jar:1.4.199]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:427) ~[h2-1.4.199.jar:1.4.199]
at org.h2.message.DbException.get(DbException.java:205) ~[h2-1.4.199.jar:1.4.199]
2019-05-22 08:33:16.226 ERROR 2276 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only] with root cause
org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:755) ~[spring-tx-5.1.6.RELEASE.jar:
As #thanhngo alread mentioned. This is how to do it.
You already have the correct annotation on the addUser method and any RuntimeException will cause the transaction to be rolled back.
Make sure that usersRespository.addUser... and authoritiesReposotory.addNew... also have the #Transactional annotation

Eclipselink OptimisticLock causing deadlocks

We have an enterprise application running on WL 12c using eclipselink as the deafult JPA provider. MS SQL server 2008 is the backend database
There is an entity on which i have used the following definition . the entity doesnt have any relationship with other entities
#Entity
#Table(name="TCALCNX")
#Cache(isolation=CacheIsolationType.ISOLATED, expiry=0, alwaysRefresh=true)
#OptimisticLocking(type=OptimisticLockingType.SELECTED_COLUMNS, selectedColumns= {#Column(name="REC_UDT_TS")})
As you can see there is an optimistic lock on a selected field which means all users can read the entity but while
updating the entity, a check is made to ensure the object hasnt changed since it was read. If it was we get a optimisticlock exception.
Whats happening in my case is when i run the application with optimisticlock on,i rarely get optmisticlock exception but high number of deadlock exceptions.
If i run the app with optimistic lock turned off am not getting any deadlock exceptions.
Internal Exception: java.sql.SQLTransactionRollbackException: [FMWGEN][SQLServer
JDBC Driver][SQLServer]Transaction (Process ID 338) was deadlocked on lock
| communication buffer resources with another process and has been chosen as the
deadlock victim. Rerun the transaction.
Error Code: 1205
what has the optimistic lock has to do with deadlocks
Ok assume that there are two transactions that read the object and modififed it . Both the transactions are updating at the same time .
if this is the case then i shud be getting the deadlock exception with the optimisticlock turned off. But am not getting
any deadlock exception when optimisticlock is turned off.
when i turn on the optimistic lock, looks like there is a lot of concurrency causing deadlock
Is it like with optimsticlock turned on , the updates are not ordered thus causing lot of concurrency
Is there a way to find out if the transactions are ordered or not in ecliselink
the backend database isolation level is read_committed.
Please dont hesitate to post any comment, there could be a clue from anyanswer from which i can get the answer
Entity
#Entity
#Table(name="TCALCNX")
#Cache(isolation=CacheIsolationType.ISOLATED, expiry=0, alwaysRefresh=true)
#OptimisticLocking(type=OptimisticLockingType.SELECTED_COLUMNS,selectedColumns= {#Column(name = "REC_UDT_TS")} )
public class CallContentEntity implements Serializable {
public static final String RECORDSTATUS_ADDED = "01";
public static final String RECORDSTATUS_UPDATED = "02";
public static final String RECORDSTATUS_MARKED_FOR_DELETION = "15";
#Id
#Column(name="CAL_ID_NR")
private String CallID;
#Column(name="CAL_CNX_B")
private byte[] CallContent;
#Column(name="REC_UDT_TS")
private Timestamp UpdateTimestamp;
#Column(name="REC_STS_CD", length=2)
private String RecordStatusCode;
#Column(name="SRC_DAT_CTR_NR", length=2)
private String SourceDataCnterNum;
#Column(name="REC_TYP_VER_NR", length=4)
private String VersionNumber;
#Column(name="REC_SEQ_NR")
private int SequenceNumber;
private static final long serialVersionUID = 1L;
public CallContentEntity() {
super();
}
public CallContentEntity(String callID) {
super();
LookUpValues lkup= LookUpValues.getInstance();
setCallID(callID);
setCallContent(null);
setRecordStatusCode(RECORDSTATUS_ADDED);
setUpdateTimestamp(new java.sql.Timestamp(Calendar.getInstance().getTimeInMillis()));
String sdatacntr= Integer.toString(lkup.getEnvironmentValue());
setSourceDataCnterNum(sdatacntr);
setVersionNumber(lkup.getLookUpValue("callcontentversion"));
setSequenceNumber(1);
}
public String getCallID() {
return this.CallID;
}
public void setCallID(String CallID) {
this.CallID = CallID;
}
public byte[] getCallContent() {
return this.CallContent;
}
public void setCallContent(byte[] CallContent) {
this.CallContent = CallContent;
}
public Timestamp getUpdateTimestamp() {
return this.UpdateTimestamp;
}
public void setUpdateTimestamp(Timestamp UpdateTimestamp) {
this.UpdateTimestamp = UpdateTimestamp;
}
public String getRecordStatusCode() {
return this.RecordStatusCode;
}
public void setRecordStatusCode(String RecordStatusCode) {
this.RecordStatusCode = RecordStatusCode;
}
public String getSourceDataCnterNum() {
return SourceDataCnterNum;
}
public void setSourceDataCnterNum(String sourceDataCnterNum) {
SourceDataCnterNum = sourceDataCnterNum;
}
public String getVersionNumber() {
return VersionNumber;
}
public void setVersionNumber(String versionNumber) {
VersionNumber = versionNumber;
}
public int getSequenceNumber() {
return SequenceNumber;
}
public void setSequenceNumber(int sequenceNumber) {
SequenceNumber = sequenceNumber;
}
Exception
Exception stack:
Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLTransactionRollbackException: [FMWGEN][SQLServer JDBC Driver][SQLServer]Transaction (Process ID 338) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
Error Code: 1205
Call: SELECT CAL_ID_NR, CAL_CNX_B, REC_STS_CD, REC_SEQ_NR, SRC_DAT_CTR_NR, REC_UDT_TS, REC_TYP_VER_NR FROM TCALCNX WHERE (CAL_ID_NR = ?)
bind => [P4F22420140806182408001244]
Query: ReadObjectQuery(name="readObject" referenceClass=CallContentEntity sql="SELECT CAL_ID_NR, CAL_CNX_B, REC_STS_CD, REC_SEQ_NR, SRC_DAT_CTR_NR, REC_UDT_TS, REC_TYP_VER_NR FROM TCALCNX WHERE (CAL_ID_NR = ?)")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:333)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:644)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:535)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1717)
at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:566)
at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:207)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:207)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:193)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.selectOneRow(DatasourceCallQueryMechanism.java:666)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectOneRowFromTable(ExpressionQueryMechanism.java:2656)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectOneRow(ExpressionQueryMechanism.java:2627)
at org.eclipse.persistence.queries.ReadObjectQuery.executeObjectLevelReadQuery(ReadObjectQuery.java:450)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1081)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1040)
at org.eclipse.persistence.queries.ReadObjectQuery.execute(ReadObjectQuery.java:418)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1128)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1449)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.executeQuery(EntityManagerImpl.java:820)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.findInternal(EntityManagerImpl.java:760)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.find(EntityManagerImpl.java:653)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.find(EntityManagerImpl.java:532)
at sun.reflect.GeneratedMethodAccessor131.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at weblogic.persistence.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:111)
at weblogic.persistence.TransactionalEntityManagerProxyImpl.invoke(TransactionalEntityManagerProxyImpl.java:82)
at weblogic.persistence.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:92)
at $Proxy99.find(Unknown Source)
at com.ups.ivr.ins.ejb.CallContentSession.Lookup(CallContentSession.java:207)
at com.ups.ivr.ins.ejb.CallContentSession_95sf62_CallContentSessionLocalImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionLocalMethodInvoker.invoke(SessionLocalMethodInvoker.java:31)
at com.ups.ivr.ins.ejb.CallContentSession_95sf62_CallContentSessionLocalImpl.Lookup(Unknown Source)
at com.ups.ivr.ins.ejb.CallManager.getCurrentCallContent(CallManager.java:402)
at com.ups.ivr.ins.ejb.CallManager_11k7mo_CallManagerLocalImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionLocalMethodInvoker.invoke(SessionLocalMethodInvoker.java:31)
at com.ups.ivr.ins.ejb.CallManager_11k7mo_CallManagerLocalImpl.getCurrentCallContent(Unknown Source)
at com.ups.ivr.ins.ejb.LookupSessionBean.Processdata(LookupSessionBean.java:184)
at com.ups.ivr.ins.ejb.LookupSessionBean_1i73wg_LookupSessionBeanLocalImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionLocalMethodInvoker.invoke(SessionLocalMethodInvoker.java:31)
at com.ups.ivr.ins.ejb.LookupSessionBean_1i73wg_LookupSessionBeanLocalImpl.Processdata(Unknown Source)
at com.ups.ivr.ins.mwproxy.ClientRequestProcessor.doPost(ClientRequestProcessor.java:140)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:751)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:242)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:216)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:132)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:338)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:221)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3292)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3262)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2171)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2097)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2075)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1514)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:254)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
Caused by: java.sql.SQLTransactionRollbackException: [FMWGEN][SQLServer JDBC Driver][SQLServer]Transaction (Process ID 338) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
at weblogic.jdbc.sqlserverbase.ddb_.b(Unknown Source)
at weblogic.jdbc.sqlserverbase.ddb_.a(Unknown Source)
at weblogic.jdbc.sqlserverbase.ddb9.b(Unknown Source)
at weblogic.jdbc.sqlserverbase.ddb9.a(Unknown Source)
at weblogic.jdbc.sqlserver.tds.ddr.v(Unknown Source)
at weblogic.jdbc.sqlserver.tds.ddr.a(Unknown Source)
at weblogic.jdbc.sqlserver.tds.ddq.a(Unknown Source)
at weblogic.jdbc.sqlserver.tds.ddr.a(Unknown Source)
at weblogic.jdbc.sqlserver.tds.ddr.a(Unknown Source)
at weblogic.jdbc.sqlserver.ddh.a(Unknown Source)
at weblogic.jdbc.sqlserverbase.ddcq.k(Unknown Source)
at weblogic.jdbc.sqlserverbase.dddm.next(Unknown Source)
at weblogic.jdbc.wrapper.ResultSet_weblogic_jdbc_sqlserverbase_dddn.next(Unknown Source)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.processResultSet(DatabaseAccessor.java:699)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:621)
... 62 more
UPDATE EXCEPTION
<2014-08-06> [P4F21420140806182553001248] <12:27:24,293> {ERROR} CallContentSession - CallContent Update Exception.
Failed to write Lookup content entry:(P4F21420140806182553001248)
Exception stack:
weblogic.transaction.RollbackException: Unexpected exception in beforeCompletion: sync=org.eclipse.persistence.transaction.JTASynchronizationListener#1c1f9da7
Internal Exception: java.sql.SQLTransactionRollbackException: [FMWGEN][SQLServer JDBC Driver][SQLServer]Transaction (Process ID 338) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
Error Code: 1205
Call: UPDATE TCALCNX SET CAL_CNX_B = ?, REC_STS_CD = ?, REC_UDT_TS = ? WHERE ((CAL_ID_NR = ?) AND (REC_UDT_TS = ?))
bind => [[B#1c1f9699, 02, 2014-08-06 12:27:22.645, P4F21420140806182553001248, 2014-08-06 12:27:21.287]
Query: UpdateObjectQuery(CALL ID :P4F21420140806182553001248
REC_UDT_TS :2014-08-06 12:27:22.645
REC_STS_CD:02
SRC_DT_CNTR:10
VERSION_NUM :001
REC_SEQ_NR:1)
at weblogic.transaction.internal.TransactionImpl.throwRollbackException(TransactionImpl.java:1884)
at weblogic.transaction.internal.ServerTransactionImpl.internalCommit(ServerTransactionImpl.java:376)
at weblogic.transaction.internal.ServerTransactionImpl.commit(ServerTransactionImpl.java:268)
at weblogic.transaction.internal.TransactionManagerImpl.commit(TransactionManagerImpl.java:308)
at weblogic.transaction.internal.TransactionManagerImpl.commit(TransactionManagerImpl.java:302)
at com.ups.ivr.ins.ejb.CallContentSession.Update(CallContentSession.java:276)
at com.ups.ivr.ins.ejb.CallContentSession_95sf62_CallContentSessionLocalImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionLocalMethodInvoker.invoke(SessionLocalMethodInvoker.java:31)
at com.ups.ivr.ins.ejb.CallContentSession_95sf62_CallContentSessionLocalImpl.Update(Unknown Source)
at com.ups.ivr.ins.ejb.CallManager.saveCall(CallManager.java:130)
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 com.ups.ivr.ins.pojo.concurrent.Task$1.run(Task.java:60)
at com.ups.ivr.ins.pojo.concurrent.Task.run(Task.java:127)
at weblogic.work.j2ee.J2EEWorkManager$WorkWithListener.run(J2EEWorkManager.java:184)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLTransactionRollbackException: [FMWGEN][SQLServer JDBC Driver][SQLServer]Transaction (Process ID 338) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
Error Code: 1205
Call: UPDATE TCALCNX SET CAL_CNX_B = ?, REC_STS_CD = ?, REC_UDT_TS = ? WHERE ((CAL_ID_NR = ?) AND (REC_UDT_TS = ?))
bind => [[B#1c1f9699, 02, 2014-08-06 12:27:22.645, P4F21420140806182553001248, 2014-08-06 12:27:21.287]
Query: UpdateObjectQuery(CALL ID :P4F21420140806182553001248
REC_UDT_TS :2014-08-06 12:27:22.645
REC_STS_CD:02
SRC_DT_CNTR:10
VERSION_NUM :001
REC_SEQ_NR:1)
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:840)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:906)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:592)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:535)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1717)
at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:253)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:207)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:193)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.updateObject(DatasourceCallQueryMechanism.java:749)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.updateObject(StatementQueryMechanism.java:432)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.updateObjectForWriteWithChangeSet(DatabaseQueryMechanism.java:1042)
at org.eclipse.persistence.queries.UpdateObjectQuery.executeCommitWithChangeSet(UpdateObjectQuery.java:84)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:287)
at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1449)
at org.eclipse.persistence.internal.sessions.CommitManager.commitChangedObjectsForClassWithChangeSet(CommitManager.java:265)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:128)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:3799)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1415)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.java:636)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1505)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3143)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:346)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:157)
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68)
at weblogic.transaction.internal.ServerSCInfo.doBeforeCompletion(ServerSCInfo.java:1259)
at weblogic.transaction.internal.ServerSCInfo.callBeforeCompletions(ServerSCInfo.java:1234)
at weblogic.transaction.internal.ServerSCInfo.startPrePrepareAndChain(ServerSCInfo.java:123)
at weblogic.transaction.internal.ServerTransactionImpl.localPrePrepareAndChain(ServerTransactionImpl.java:1355)
at weblogic.transaction.internal.ServerTransactionImpl.globalPrePrepare(ServerTransactionImpl.java:2172)
at weblogic.transaction.internal.ServerTransactionImpl.internalCommit(ServerTransactionImpl.java:300)
at weblogic.transaction.internal.ServerTransactionImpl.commit(ServerTransactionImpl.java:267)
at weblogic.transaction.internal.TransactionManagerImpl.commit(TransactionManagerImpl.java:307)
at weblogic.transaction.internal.TransactionManagerImpl.commit(TransactionManagerImpl.java:301)
at com.ups.ivr.ins.ejb.CallContentSession.Update(CallContentSession.java:276)
at com.ups.ivr.ins.ejb.CallContentSession_95sf62_CallContentSessionLocalImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionLocalMethodInvoker.invoke(SessionLocalMethodInvoker.java:31)
at com.ups.ivr.ins.ejb.CallContentSession_95sf62_CallContentSessionLocalImpl.Update(Unknown Source)
at com.ups.ivr.ins.ejb.CallManager.saveCall(CallManager.java:130)
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 com.ups.ivr.ins.pojo.concurrent.Task$1.run(Task.java:60)
at com.ups.ivr.ins.pojo.concurrent.Task.run(Task.java:126)
... 3 more
Caused by: java.sql.SQLTransactionRollbackException: [FMWGEN][SQLServer JDBC Driver][SQLServer]Transaction (Process ID 338) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
at weblogic.jdbc.sqlserverbase.ddb_.b(Unknown Source)
at weblogic.jdbc.sqlserverbase.ddb_.a(Unknown Source)
at weblogic.jdbc.sqlserverbase.ddb9.b(Unknown Source)
at weblogic.jdbc.sqlserverbase.ddb9.a(Unknown Source)
at weblogic.jdbc.sqlserver.tds.ddr.v(Unknown Source)
at weblogic.jdbc.sqlserver.tds.ddr.a(Unknown Source)
at weblogic.jdbc.sqlserver.tds.ddq.a(Unknown Source)
at weblogic.jdbc.sqlserver.tds.ddr.a(Unknown Source)
at weblogic.jdbc.sqlserver.ddj.m(Unknown Source)
at weblogic.jdbc.sqlserverbase.ddel.e(Unknown Source)
at weblogic.jdbc.sqlserverbase.ddel.a(Unknown Source)
at weblogic.jdbc.sqlserverbase.ddde.a(Unknown Source)
at weblogic.jdbc.sqlserverbase.ddel.v(Unknown Source)
at weblogic.jdbc.sqlserverbase.ddel.x(Unknown Source)
at weblogic.jdbc.sqlserverbase.ddde.executeUpdate(Unknown Source)
at weblogic.jdbc.wrapper.PreparedStatement.executeUpdate(PreparedStatement.java:167)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:831)
... 54 more
I'm not sure what this has to do with Optimistic locking (it likely does not). You should reduce what you are doing within your transactions so that any locks they obtain are held for shorter periods, such as only calling flush when it is absolutely required. Flush causes statements to be issued to the DB which will obtain locks earlier than might be needed, and will be held until the transaction fully commits, making it easier for transactions to conflict.
Optimistic locking in EclipseLink does nothing special other than add the changed field value to the where clause when modifying the corresponding entity. This does not affect the ordering of statements. It could be that your application's handling of optimistic lock exceptions is causing a delay or extra concurrent load if it retries the same operations over and over on a contentious row.
Optimistic Locking is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) and check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic.
When using optimistic locking we still have a deadlock situation which is not covered by the lock reordering:
Tx1 and Tx2 transactions executing in parallel on two nodes N1 and N2 and writing the keys {a,b}
consistentHash(a) = {N3} and consistentHash(b) = {N4}
with some right timing, during prepare time it is possible for these two transactions to deadlock:
Tx1 lock acquired on "a" # N3
Tx2 lock acquired on "b" # N4
Tx1 cannot progress acquiring lock on "b" # N4, that lock is acquired by Tx2
Tx2 cannot acquire lock on "a" # N3 as that lock is held by Tx1
Tx1 and Tx2 are waiting for each other ⇒ deadlock
A fast solution is to change Optimistic Lock to Pessimistic Lock in order to handle the situations, else i suggest you this link.

JPA #ElementCollection [List<String>] deletion error, using play Framework 1.2.7

I want to delete a model object and that object has a list of string collection. I am using Play Framework 1.2.7.
Class structure as follows :
#Entity
#Table(name = "DATASET_CORE")
#NamedQueries(value = {
#NamedQuery(name = "datasetcore.delete", query = "DELETE FROM DataSetCore dataCore WHERE dataCore.id = :dataCoreId")
})
public class DataSetCore extends Model {
:
#Required(message = "dataset.keyword.required")
#Column(nullable = false,name = "KEYWORD")
#ElementCollection(fetch = FetchType.LAZY)
public List<String> keywords;
:
}
My Deletion code as follows:
Query q = Publish.em().createNamedQuery("datasetcore.delete");
q.setParameter("dataCoreId", dataSet.id);
q.executeUpdate();
It gives following error:
15:33:30,053 WARN ~ SQL Error: 23503, SQLState: 23503
15:33:30,053 ERROR ~ Referential integrity constraint violation: "FK9B153AF2E51FF179: PUBLIC.DATASETCORE_KEYWORDS FOREIGN KEY(DATASETCORE_ID) REFERENCES PUBLIC.DATASET_CORE(ID) (2)"; SQL sta
tement:
delete from DATASET_CORE where id=? [23503-166]
ERROR.....
javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute update query
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1389)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1317)
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1399)
at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:108)
at com.hbase.metadata.services.DataSetCoreService.delete(DataSetCoreService.java:39)
at com.hbase.metadata.services.MetaDataCoreService.delete(MetaDataCoreService.java:241)
at com.hbase.ref.MetaDataCoreTestCase.deleteMetaData(MetaDataCoreTestCase.java:61)
at com.hbase.ref.MetaDataCoreTestCase.executeTest(MetaDataCoreTestCase.java:39)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at play.test.PlayJUnitRunner$StartPlay$2$1.evaluate(PlayJUnitRunner.java:114)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at play.test.PlayJUnitRunner.run(PlayJUnitRunner.java:58)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:24)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at org.junit.runner.JUnitCore.run(JUnitCore.java:136)
at org.junit.runner.JUnitCore.run(JUnitCore.java:117)
at play.test.TestEngine.run(TestEngine.java:112)
at controllers.TestRunner$1.doJobWithResult(TestRunner.java:71)
at controllers.TestRunner$1.doJobWithResult(TestRunner.java:1)
at play.jobs.Job.call(Job.java:146)
at play.jobs.Job$1.call(Job.java:66)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:207)
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:619)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute update query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.hql.ast.exec.BasicExecutor.execute(BasicExecutor.java:110)
at org.hibernate.hql.ast.QueryTranslatorImpl.executeUpdate(QueryTranslatorImpl.java:423)
at org.hibernate.engine.query.HQLQueryPlan.performExecuteUpdate(HQLQueryPlan.java:283)
at org.hibernate.impl.SessionImpl.executeUpdate(SessionImpl.java:1288)
at org.hibernate.impl.QueryImpl.executeUpdate(QueryImpl.java:117)
at org.hibernate.ejb.QueryImpl.internalExecuteUpdate(QueryImpl.java:188)
at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:99)
... 46 more
Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK9B153AF2E51FF179: PUBLIC.DATASETCORE_KEYWORDS FOREIGN KEY(DATASETCORE_ID) REFERENCES PUBLIC.DATASET_CO
RE(ID) (2)"; SQL statement:
delete from DATASET_CORE where id=? [23503-166]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
at org.h2.message.DbException.get(DbException.java:169)
at org.h2.message.DbException.get(DbException.java:146)
at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:414)
at org.h2.constraint.ConstraintReferential.checkRowRefTable(ConstraintReferential.java:431)
at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:307)
at org.h2.table.Table.fireConstraints(Table.java:862)
at org.h2.table.Table.fireAfterRow(Table.java:879)
at org.h2.command.dml.Delete.update(Delete.java:99)
at org.h2.command.CommandContainer.update(CommandContainer.java:73)
at org.h2.command.Command.executeUpdate(Command.java:226)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:143)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:129)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105)
at org.hibernate.hql.ast.exec.BasicExecutor.execute(BasicExecutor.java:101)
... 52 more
I am using MySQL as a database. In database it's create a joining table. Script of that generated table is:
CREATE TABLE `datasetcore_keywords` (
`DataSetCore_id` bigint(20) NOT NULL,
`KEYWORD` varchar(255) NOT NULL,
KEY `FK9B153AF2E51FF179` (`DataSetCore_id`),
CONSTRAINT `FK9B153AF2E51FF179` FOREIGN KEY (`DataSetCore_id`) REFERENCES `dataset_core` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Can anyone help me regarding this issue.
This is copied from your error:
PUBLIC.DATASETCORE_KEYWORDS FOREIGN KEY(DATASETCORE_ID)
REFERENCES PUBLIC.DATASET_CORE(ID)
Its showing that the row you are trying to delete is referenced from another table named DATASETCORE_KEYWORDS the column DATASETCORE_ID. You have to delete that row from the table first, and only then you can do the current delete operation.