Eclipse Link JPA native update query thowring deadlock exception - jpa

I am using Eclipselink JPA with JTA container lever transaction and trying to execute the below code
public int loadTargetTables() throws Exception {
String sNavtive = "INSERT INTO TRGT_TABLE SELECT * FROM SRC_TABLE";
int results = this.em.createNativeQuery(sNavtive).executeUpdate();
return results;
}
and note that source table and tartget table both are identical in no od columns and data types.
I am getting bellow issue
[EL Finer]: 2014-12-29 11:13:04.681--Connection(17529256)--Thread(Thread[[ACTIVE] ExecuteThread: '15' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--Begin batch statements
[EL Fine]: 2014-12-29 11:13:04.681--Connection(17529256)--Thread(Thread[[ACTIVE] ExecuteThread: '15' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--INSERT INTO TRGT_TABLE select * FROM SRC_TABLE
[EL Finer]: 2014-12-29 11:13:04.681--Connection(17529256)--Thread(Thread[[ACTIVE] ExecuteThread: '15' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--End Batch Statements
[EL Finest]: 2014-12-29 11:13:04.681--Thread(Thread[[ACTIVE] ExecuteThread: '15' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--reconnecting to external connection pool
[EL Fine]: 2014-12-29 11:14:01.625--Thread(Thread[[ACTIVE] ExecuteThread: '15' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--SELECT 1 FROM DUAL
[EL Warning]: 2014-12-29 11:14:01.641--Thread(Thread[[ACTIVE] ExecuteThread: '15' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.BatchUpdateException: error occurred during batching: ORA-02049: timeout : distributed transaction waiting for a lock
Error Code: 17081
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeJDK12BatchStatement(DatabaseAccessor.java:873)
at org.eclipse.persistence.internal.databaseaccess.DynamicSQLBatchWritingMechanism.executeBatchedStatements(DynamicSQLBatchWritingMechanism.java:143)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.writesCompleted(DatabaseAccessor.java:1707)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.commitTransaction(DatabaseAccessor.java:408)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicCommitTransaction(AbstractSession.java:567)
at org.eclipse.persistence.sessions.server.ClientSession.basicCommitTransaction(ClientSession.java:131)
at org.eclipse.persistence.internal.sessions.AbstractSession.commitTransaction(AbstractSession.java:762)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitTransaction(UnitOfWorkImpl.java:1574)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitTransaction(RepeatableWriteUnitOfWork.java:649)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitTransactionAfterWriteChanges(UnitOfWorkImpl.java:1589)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:354)
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(Unknown Source)
at weblogic.transaction.internal.ServerSCInfo.callBeforeCompletions(Unknown Source)
at weblogic.transaction.internal.ServerSCInfo.startPrePrepareAndChain(Unknown Source)
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.ejb.container.internal.BaseLocalObject.postInvoke1(BaseLocalObject.java:331)
at weblogic.ejb.container.internal.BaseLocalObject.__WL_postInvokeTxRetry(BaseLocalObject.java:202)
at weblogic.ejb.container.internal.SessionLocalMethodInvoker.invoke(SessionLocalMethodInvoker.java:44)

as mentioned in the error description: distributed transaction waiting for a lock
probably you have some other instances of EntityManager(em) or uncommited or unrolled back transactions which are working on TRGT_TABLE or SRC_TABLE tables or they are in used by ther sessions in database

Related

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

Connection not releasing for StoredProcedureQuery without #Transactional

I have the following service which simply logs an error message to the database. When I do not have #Transactional on the method, the connection stays active until all the connections are used up. All the StoredProcedureQuery calls that return a result do not have this problem.
Why do I need to mark the method as #Transactional to have it release the connection?
#Service
public class SSOErrorLogServiceImpl implements SSOErrorLogService {
#PersistenceContext
private EntityManager em;
#Override
#Transactional
public void logError(String errorMessage, String request){
StoredProcedureQuery proc = em.createNamedStoredProcedureQuery("dbo.spSSOLogError");
proc.setParameter("errorMessage", errorMessage);
proc.setParameter("request", request);
proc.execute();
}
}
DataConfig
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory
= new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(reflexDataSource());
entityManagerFactory.setPackagesToScan("com.company.platform.jpa");
entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
Properties additionalProperties = new Properties();
additionalProperties.put("eclipselink.weaving", "false");
entityManagerFactory.setJpaProperties(additionalProperties);
return entityManagerFactory;
}
#Bean
public HikariDataSource reflexDataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setLeakDetectionThreshold(20000);
dataSource.setMaximumPoolSize(20);
dataSource.setConnectionTimeout(5000);
dataSource.setRegisterMbeans(false);
dataSource.setInitializationFailFast(false);
dataSource.setDriverClassName(driver);
dataSource.setJdbcUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
Logs without transaction (excerpt)
[EL Finer]: connection: 2016-09-30 14:33:16.955--ServerSession(317574415)--Thread(Thread[Test worker,5,main])--client acquired: 1151058631
[EL Finer]: transaction: 2016-09-30 14:33:16.962--ClientSession(1151058631)--Thread(Thread[Test worker,5,main])--acquire unit of work: 544160013
[EL Finest]: query: 2016-09-30 14:33:16.962--UnitOfWork(544160013)--Thread(Thread[Test worker,5,main])--Execute query ResultSetMappingQuery(name="dbo.spSSOLogError" )
[EL Finest]: connection: 2016-09-30 14:33:16.963--ServerSession(317574415)--Connection(1107704332)--Thread(Thread[Test worker,5,main])--Connection acquired from connection pool [read].
[EL Finest]: connection: 2016-09-30 14:33:16.963--ServerSession(317574415)--Thread(Thread[Test worker,5,main])--reconnecting to external connection pool
[EL Fine]: sql: 2016-09-30 14:33:16.963--ServerSession(317574415)--Connection(539538496)--Thread(Thread[Test worker,5,main])--EXECUTE dbo.spSSOLogError #errorMessage = ?, #request = ?
bind => [Message, Request]
2016-09-30 14:33:16,984 | TRACE | org.springframework.test.context.TestContextManager:394 - afterTestMethod(): instance [com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest#314c32e8], method [public void com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest.test_logError()], exception [null]
2016-09-30 14:33:16,985 | DEBUG | org.springframework.test.context.support.DirtiesContextTestExecutionListener:94 - After test method: context [DefaultTestContext#6cce3af3 testClass = SSOErrorLogServiceTest, testInstance = com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest#314c32e8, testMethod = test_logError#SSOErrorLogServiceTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#37770c96 testClass = SSOErrorLogServiceTest, locations = '{}', classes = '{class com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest$Config}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class dirties context [false], class mode [null], method dirties context [false].
2016-09-30 14:33:16,985 | TRACE | org.springframework.test.context.TestContextManager:437 - afterTestClass(): class [class com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest]
2016-09-30 14:33:16,986 | DEBUG | org.springframework.test.context.support.DirtiesContextTestExecutionListener:126 - After test class: context [DefaultTestContext#6cce3af3 testClass = SSOErrorLogServiceTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#37770c96 testClass = SSOErrorLogServiceTest, locations = '{}', classes = '{class com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest$Config}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], dirtiesContext [false].
Logs with #Transaction
[EL Finer]: transaction: 2016-09-30 14:30:50.747--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--begin unit of work flush
[EL Finer]: transaction: 2016-09-30 14:30:50.747--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--end unit of work flush
[EL Finest]: query: 2016-09-30 14:30:50.747--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--Execute query ResultSetMappingQuery(name="dbo.spSSOLogError" )
[EL Finest]: connection: 2016-09-30 14:30:50.748--ServerSession(1432568628)--Connection(708660831)--Thread(Thread[Test worker,5,main])--Connection acquired from connection pool [default].
[EL Finer]: transaction: 2016-09-30 14:30:50.748--ClientSession(287210054)--Connection(708660831)--Thread(Thread[Test worker,5,main])--begin transaction
[EL Finest]: connection: 2016-09-30 14:30:50.748--ClientSession(287210054)--Thread(Thread[Test worker,5,main])--reconnecting to external connection pool
[EL Fine]: sql: 2016-09-30 14:30:50.75--ClientSession(287210054)--Connection(29007067)--Thread(Thread[Test worker,5,main])--EXECUTE dbo.spSSOLogError #errorMessage = ?, #request = ?
bind => [Message, Request]
2016-09-30 14:30:50,772 | TRACE | org.springframework.transaction.interceptor.TransactionAspectSupport:519 - Completing transaction for [com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceImpl.logError]
2016-09-30 14:30:50,772 | TRACE | org.springframework.transaction.support.AbstractPlatformTransactionManager:926 - Triggering beforeCommit synchronization
2016-09-30 14:30:50,772 | TRACE | org.springframework.transaction.support.AbstractPlatformTransactionManager:939 - Triggering beforeCompletion synchronization
2016-09-30 14:30:50,772 | DEBUG | org.springframework.transaction.support.AbstractPlatformTransactionManager:755 - Initiating transaction commit
2016-09-30 14:30:50,773 | DEBUG | org.springframework.orm.jpa.JpaTransactionManager:512 - Committing JPA transaction on EntityManager [org.eclipse.persistence.internal.jpa.EntityManagerImpl#8f90fd5]
[EL Finer]: transaction: 2016-09-30 14:30:50.773--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--begin unit of work commit
[EL Finer]: transaction: 2016-09-30 14:30:50.773--ClientSession(287210054)--Connection(29007067)--Thread(Thread[Test worker,5,main])--commit transaction
[EL Finest]: connection: 2016-09-30 14:30:50.775--ServerSession(1432568628)--Connection(708660831)--Thread(Thread[Test worker,5,main])--Connection released to connection pool [default].
[EL Finer]: transaction: 2016-09-30 14:30:50.775--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--end unit of work commit
[EL Finer]: transaction: 2016-09-30 14:30:50.775--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--resume unit of work
2016-09-30 14:30:50,775 | TRACE | org.springframework.transaction.support.AbstractPlatformTransactionManager:952 - Triggering afterCommit synchronization
2016-09-30 14:30:50,775 | TRACE | org.springframework.transaction.support.AbstractPlatformTransactionManager:968 - Triggering afterCompletion synchronization
2016-09-30 14:30:50,775 | TRACE | org.springframework.transaction.support.TransactionSynchronizationManager:331 - Clearing transaction synchronization
2016-09-30 14:30:50,776 | TRACE | org.springframework.transaction.support.TransactionSynchronizationManager:243 - Removed value [org.springframework.orm.jpa.EntityManagerHolder#4569d6c9] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean#33d8b566] from thread [Test worker]
2016-09-30 14:30:50,776 | TRACE | org.springframework.transaction.support.TransactionSynchronizationManager:243 - Removed value [org.springframework.jdbc.datasource.ConnectionHolder#53d1206a] for key [JDBC URL = jdbc:sqlserver://somehost:1433;databaseName=Database, Username = test, partitions = 1, max (per partition) = 10, min (per partition) = 0, idle max age = 60 min, idle test period = 240 min, strategy = DEFAULT] from thread [Test worker]
2016-09-30 14:30:50,776 | DEBUG | org.springframework.orm.jpa.JpaTransactionManager:600 - Closing JPA EntityManager [org.eclipse.persistence.internal.jpa.EntityManagerImpl#8f90fd5] after transaction
2016-09-30 14:30:50,776 | DEBUG | org.springframework.orm.jpa.EntityManagerFactoryUtils:432 - Closing JPA EntityManager
[EL Finer]: transaction: 2016-09-30 14:30:50.776--UnitOfWork(1448667590)--Thread(Thread[Test worker,5,main])--release unit of work
[EL Finer]: connection: 2016-09-30 14:30:50.776--ClientSession(287210054)--Thread(Thread[Test worker,5,main])--client released
2016-09-30 14:30:50,776 | TRACE | org.springframework.test.context.TestContextManager:394 - afterTestMethod(): instance [com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest#314c32e8], method [public void com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest.test_logError()], exception [null]
2016-09-30 14:30:50,777 | DEBUG | org.springframework.test.context.support.DirtiesContextTestExecutionListener:94 - After test method: context [DefaultTestContext#6cce3af3 testClass = SSOErrorLogServiceTest, testInstance = com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest#314c32e8, testMethod = test_logError#SSOErrorLogServiceTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#37770c96 testClass = SSOErrorLogServiceTest, locations = '{}', classes = '{class com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest$Config}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class dirties context [false], class mode [null], method dirties context [false].
2016-09-30 14:30:50,777 | TRACE | org.springframework.test.context.TestContextManager:437 - afterTestClass(): class [class com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest]
2016-09-30 14:30:50,778 | DEBUG | org.springframework.test.context.support.DirtiesContextTestExecutionListener:126 - After test class: context [DefaultTestContext#6cce3af3 testClass = SSOErrorLogServiceTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#37770c96 testClass = SSOErrorLogServiceTest, locations = '{}', classes = '{class com.somecompany.platform.jpa.ssoerrorlog.SSOErrorLogServiceTest$Config}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], dirtiesContext [false].
Did you try changing #PersistenceContext to #PersistanceUnit?
EntityManagers obtained via #PersistenceContext are Container Managed Entity Manager as the container will be responsible for managing "Entity Manager" while EntityManagers obtained via #PersistenceUnit / entityManagerFactory.createEntityManager() are Application Managed Entity Manager and developer has to manage certain things in code (for e.g. releasing the resources acquired by EntityManager).
Try release the query.
query.unwrap(ProcedureOutputs.class).release();
We were facing the same issue with the execute() call. The connection was not getting closed. Looking at the code made it more clear: execute()
Calling the executeUpdate() solved it.

Criteria query cache caching in Eclipselink?

Iam using criteria queries with EclipseLink as JPA . I need to cache the query results based on their parameters . When I used query.setHint("eclipselink.QUERY_RESULTS_CACHE", "TRUE") it still fires query to the database. How can I use it in context of criteria queries ?
Here I set my query and their hints and addNamedQuery
Query query = psEntityManager.getEntityManager().createQuery(criteriaQuery);// Creating Query to supply Values
query.setHint("eclipselink.QUERY_RESULTS_CACHE", "TRUE");
query.setHint(QueryHints.QUERY_TYPE,QueryType.ReadObject);
psEntityManager.getEntityManager().getEntityManagerFactory().addNamedQuery("query1", query);
Here is my output :
Query1-----------
[EL Fine]: sql: 2013-10-10 21:33:35.495--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, ADDRESSLINE1, ADDRESSLINE2, PHONENUMBER, fkCityId, fkPersonId FROM ADDRESS WHERE (fkPersonId = ?)
bind => [2]
[EL Fine]: sql: 2013-10-10 21:33:35.527--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, CITYNAME, PINCODE, fkStateId FROM CITY WHERE (PRIMARYKEY = ?)
bind => [2]
[EL Fine]: sql: 2013-10-10 21:33:35.528--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, STATENAME FROM STATE WHERE (PRIMARYKEY = ?)
bind => [1]
[EL Fine]: sql: 2013-10-10 21:33:35.531--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, AGE, DOB, FIRSTNAME, LASTNAME, SEX, TIMESTAMP, fkDepartmentId FROM PERSON WHERE (PRIMARYKEY = ?)
bind => [2]
[EL Fine]: sql: 2013-10-10 21:33:35.541--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, DEPTNAME FROM DEPARTMENT WHERE (PRIMARYKEY = ?)
bind => [2]
[EL Fine]: sql: 2013-10-10 21:33:35.547--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, CITYNAME, PINCODE, fkStateId FROM CITY WHERE (PRIMARYKEY = ?)
bind => [5]
[EL Fine]: sql: 2013-10-10 21:33:35.548--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, STATENAME FROM STATE WHERE (PRIMARYKEY = ?)
bind => [3]
[EL Fine]: sql: 2013-10-10 21:33:35.551--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, CITYNAME, PINCODE, fkStateId FROM CITY WHERE (PRIMARYKEY = ?)
bind => [8]
[EL Fine]: sql: 2013-10-10 21:33:35.553--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, STATENAME FROM STATE WHERE (PRIMARYKEY = ?)
bind => [4]
Query2-----------
[EL Fine]: sql: 2013-10-10 21:33:35.557--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, ADDRESSLINE1, ADDRESSLINE2, PHONENUMBER, fkCityId, fkPersonId FROM ADDRESS WHERE (fkPersonId = ?)
bind => [2]
Query3-----------
[EL Fine]: sql: 2013-10-10 21:33:35.56--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, ADDRESSLINE1, ADDRESSLINE2, PHONENUMBER, fkCityId, fkPersonId FROM ADDRESS WHERE (fkPersonId = ?)
bind => [2]
Query4-----------
[EL Fine]: sql: 2013-10-10 21:33:35.563--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, ADDRESSLINE1, ADDRESSLINE2, PHONENUMBER, fkCityId, fkPersonId FROM ADDRESS WHERE (fkPersonId = ?)
bind => [2]
Remove the query.setHint(QueryHints.QUERY_TYPE,QueryType.ReadObject), or call it first. The query_type changes the underlying query object, and not all the hints might be copied into the new object. It seems unnecessary anyway.

Bulk update with datanucleus errors out

I'm trying to use the JDOQL bulk update in datanucleus, but I get the following exception,
12/08/13 13:06:56 INFO DataNucleus.Persistence: Property datanucleus.cache.level2 unknown - will be ignored
12/08/13 13:06:56 INFO DataNucleus.Persistence: ================= Persistence Configuration ===============
12/08/13 13:06:56 INFO DataNucleus.Persistence: DataNucleus Persistence Factory - Vendor: "DataNucleus" Version: "2.2.5"
12/08/13 13:06:56 INFO DataNucleus.Persistence: DataNucleus Persistence Factory initialised for datastore URL="jdbc:derby:;databaseName=metastore_db;create=true" driver="org.apache.derby.jdbc.EmbeddedDriver" userName="APP"
12/08/13 13:06:56 INFO DataNucleus.Persistence: ===========================================================
12/08/13 13:06:57 INFO Datastore.Schema: Initialising Catalog "", Schema "APP" using "None" auto-start option
12/08/13 13:06:57 INFO Datastore.Schema: Catalog "", Schema "APP" initialised - managing 0 classes
12/08/13 13:06:57 INFO DataNucleus.MetaData: Registering listener for metadata initialisation
Query to be executed: UPDATE myDomain.MTable t SET t.tableName = 'tmp3' WHERE t.tableName == 'tmp'
12/08/13 13:06:57 INFO DataNucleus.JDO: Exception thrown
JPQL UPDATE query has no update clause! Query should be like "UPDATE Entity e SET e.param = new_value WHERE [where-clause]"
org.datanucleus.exceptions.NucleusUserException: JPQL UPDATE query has no update clause! Query should be like "UPDATE Entity e SET e.param = new_value WHERE [where-clause]"
at org.datanucleus.query.JDOQLSingleStringParser$Compiler.compileUpdate(JDOQLSingleStringParser.java:236)
at org.datanucleus.query.JDOQLSingleStringParser$Compiler.compileSelect(JDOQLSingleStringParser.java:160)
at org.datanucleus.query.JDOQLSingleStringParser$Compiler.compile(JDOQLSingleStringParser.java:125)
at org.datanucleus.query.JDOQLSingleStringParser$Compiler.access$000(JDOQLSingleStringParser.java:114)
at org.datanucleus.query.JDOQLSingleStringParser.parse(JDOQLSingleStringParser.java:106)
at org.datanucleus.store.query.AbstractJDOQLQuery.(AbstractJDOQLQuery.java:108)
at org.datanucleus.store.rdbms.query.JDOQLQuery.(JDOQLQuery.java:119)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.datanucleus.plugin.NonManagedPluginRegistry.createExecutableExtension(NonManagedPluginRegistry.java:597)
at org.datanucleus.plugin.PluginManager.createExecutableExtension(PluginManager.java:324)
at org.datanucleus.store.query.QueryManager.newQuery(QueryManager.java:264)
at org.datanucleus.jdo.JDOPersistenceManager.newQuery(JDOPersistenceManager.java:1272)
I'm using DN-core-2.2.4, DN-RDBMS-2.2.4, DN-Enhancer-2.1.3 and DN-ConnectionPool-2.0.3.
The code snippet that I fires the update is as follows,
openTransaction();
Query q = pm.newQuery("javax.jdo.query.JDOQL", query);
q.compile();
Collection<?> result = (Collection<?>) q.execute();
committed = commitTransaction();
Any pointers on what I'm doing wrong.
My query is of the form "UPDATE myDomain.A t SET t.tableName = 'tmp3' WHERE t.tableName == 'tmp'"

How to properly create Nested Join using Criteria Builder

I have Three Entities School, Department, Program and whenever i tried to Join two of these entities, the third one gets referenced and so i am looking for an example using the criteria builder on how to properly start at a Root<> entity and Join properly.
My School entity is the one causing the problem.
public class School {
#NotNull
private String name;
#NotNull
private String code;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "schoolDepartment")
private Set<Department> departments = new HashSet<Department>();
#OneToMany(cascade = CascadeType.ALL, mappedBy = "school")
private Set<Program> programs = new HashSet<Program>();
}
Program Entity
public class Program {
#NotNull
#Size(min = 0, max = 300)
private String name;
#NotNull
#Size(min = 0)
private String description;
private String code;
#Enumerated(EnumType.STRING)
private ProgramType programType;
#ManyToOne
private School school;
My failing attempt to Only join the two entities above and EclipseLink goes and references the third?
// FROM program JOIN School
Root<Program> program = cq.from(Program.class);
Join<School,Program> school = program.join("school" , JoinType.INNER);
//Join<School, Department> departmentJoin = school.join("schoolDepartment", JoinType.LEFT);
// SELECT task as Task, person as Person, ...
cq.multiselect(program,school);
return program; // EclipseLink requires a joined entity for the count
The full stack trace which includes the SQL generated. Notice how it starts referencing the School entity and then calls a ReadAllObjectQuery on the Department entity?
[EL Fine]: sql: 2012-05-06 17:34:52.886--ServerSession(1839972036)--Connection(131165903)--Thread(Thread["http-bio-8080"-exec-3,5,main])--SELECT t0.id, t0.CODE, t0.NAME, t0.version, t1.programID, t1.ACTIVE, t1.CODE, t1.DESCRIPTION, t1.NAME, t1.PROGRAMTYPE, t1.REQUIREDCREDITS, t1.version, t1.SCHOOL_id FROM SCHOOL t0 LEFT OUTER JOIN PROGRAM t1 ON (t1.SCHOOL_id = t0.id), SCHOOL t2 WHERE (t2.id = t1.SCHOOL_id)
[EL Finest]: connection: 2012-05-06 17:34:52.888--ServerSession(1839972036)--Connection(354961667)--Thread(Thread["http-bio-8080"-exec-3,5,main])--Connection released to connection pool [read].
2012-05-06 17:34:52,896 ["http-bio-8080"-exec-3] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.School': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.School.entityManager
2012-05-06 17:34:52,896 ["http-bio-8080"-exec-3] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
2012-05-06 17:34:52,899 ["http-bio-8080"-exec-3] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.School': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.School.entityManager
2012-05-06 17:34:52,900 ["http-bio-8080"-exec-3] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
2012-05-06 17:34:52,901 ["http-bio-8080"-exec-3] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.School': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.School.entityManager
2012-05-06 17:34:52,901 ["http-bio-8080"-exec-3] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
2012-05-06 17:34:52,902 ["http-bio-8080"-exec-3] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Program': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Program.entityManager
2012-05-06 17:34:52,903 ["http-bio-8080"-exec-3] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
[EL Finest]: query: 2012-05-06 17:34:52.904--ServerSession(1839972036)--Thread(Thread["http-bio-8080"-exec-3,5,main])--Execute query ReadObjectQuery(name="school" referenceClass=School )
2012-05-06 17:34:52,908 ["http-bio-8080"-exec-3] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Program': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Program.entityManager
2012-05-06 17:34:52,908 ["http-bio-8080"-exec-3] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
[EL Finest]: transaction: 2012-05-06 17:34:52.908--UnitOfWork(2138845270)--Thread(Thread["http-bio-8080"-exec-3,5,main])--[EL Finest]: query: 2012-05-06 17:34:52.91--ServerSession(1839972036)--Thread(Thread["http-bio-8080"-exec-3,5,main])--Execute query ReadAllQuery(name="departments" referenceClass=Department )
[EL Finest]: connection: 2012-05-06 17:34:52.911--ServerSession(1839972036)--Connection(32490450)--Thread(Thread["http-bio-8080"-exec-3,5,main])--Connection acquired from connection pool [read].
[EL Finest]: connection: 2012-05-06 17:34:52.911--ServerSession(1839972036)--Thread(Thread["http-bio-8080"-exec-3,5,main])--reconnecting to external connection pool
[EL Fine]: sql: 2012-05-06 17:34:52.912--ServerSession(1839972036)--Connection(606146812)--Thread(Thread["http-bio-8080"-exec-3,5,main])--SELECT id, ACTIVE, CODE, DESCRIPTION, NAME, version, SCHOOLDEPARTMENT_id FROM DEPARTMENT WHERE (SCHOOLDEPARTMENT_id = ?)
bind => [1]
[EL Finest]: connection: 2012-05-06 17:34:52.913--ServerSession(1839972036)--Connection(32490450)--Thread(Thread["http-bio-8080"-exec-3,5,main])--Connection released to connection pool [read].
2012-05-06 17:34:52,914 ["http-bio-8080"-exec-3] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Department': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Department.entityManager
2012-05-06 17:34:52,914 ["http-bio-8080"-exec-3] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
[EL Finest]: query: 2012-05-06 17:34:52.915--ServerSession(1839972036)--Thread(Thread["http-bio-8080"-exec-3,5,main])--Execute query ReadObjectQuery(name="schoolDepartment" referenceClass=School )
[EL Finest]: query: 2012-05-06 17:34:52.915--ServerSession(1839972036)--Thread(Thread["http-bio-8080"-exec-3,5,main])--Execute query ReadAllQuery(name="programs" referenceClass=Program )
[EL Finest]: connection: 2012-05-06 17:34:52.916--ServerSession(1839972036)--Connection(63558014)--Thread(Thread["http-bio-8080"-exec-3,5,main])--Connection acquired from connection pool [read].
[EL Finest]: connection: 2012-05-06 17:34:52.916--ServerSession(1839972036)--Thread(Thread["http-bio-8080"-exec-3,5,main])--reconnecting to external connection pool
[EL Fine]: sql: 2012-05-06 17:34:52.917--ServerSession(1839972036)--Connection(920168739)--Thread(Thread["http-bio-8080"-exec-3,5,main])--SELECT programID, ACTIVE, CODE, DESCRIPTION, NAME, PROGRAMTYPE, REQUIREDCREDITS, version, SCHOOL_id FROM PROGRAM WHERE (SCHOOL_id = ?)
I added fetch = FetchType.Eager to each OneToMany relationships as it was Lazy Loading all referencing entities. Dont know if this is a performance issue or not but i figured i would need those columns anyways