Update native query is too slow - spring

I am using Hibernate with native query to update a field in a table with 17000 rows in Oracle.
When I execute the query on Toad, it takes 0.5s to be executed and with the below code no finish ever.
Query query = em.createNativeQuery("UPDATE table SET field= LEAST(NUMERADOR/DENOMINADO, ? )");
query.setParameter(1, value);
query.executeUpdate();
This is the trace:
10-08 14:15:59 DEBUG JpaTransactionManager - Creating new transaction with name [es.package.app.repository.jpa.JPAValorMaximo.update]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
10-08 14:15:59 DEBUG JpaTransactionManager - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl#405264e8] for JPA transaction
10-08 14:15:59 DEBUG AbstractTransactionImpl - begin
10-08 14:15:59 DEBUG LogicalConnectionImpl - Obtaining JDBC connection
10-08 14:15:59 DEBUG LogicalConnectionImpl - Obtained JDBC connection
10-08 14:15:59 DEBUG JdbcTransaction - initial autocommit status: true
10-08 14:15:59 DEBUG JdbcTransaction - disabling autocommit
10-08 14:15:59 DEBUG JpaTransactionManager - Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle#1bbb3b9e]
10-08 14:15:59 DEBUG SQL - UPDATE table SET field= LEAST(NUMERADOR/DENOMINADO, ? )
Hibernate: UPDATE table SET field= LEAST(NUMERADOR/DENOMINADO, ? )
thanks

Related

Not fetch a LAZY relation if I call from a method which calls after another Transactional method

In my Spring Boot 2.2.5.RELEASE application I have a problem when I try to fetch a LAZY field.
The problem occurs in a service method, createWayBillFromInvoice, which marked as #Transactional.
Case A: I call this method from a controller directly it executes with no problem.
Case B: I call the same method from another service method which is not itself Transactional
my LAZY fields not fetch.
So I assume it is about Transaction management but I could not find the reason.
The method where my LAZY fields not fetched (and fetched in a direct-call):
#Transactional
public createWayBillFromInvoice(){
Invoice invoice = invoiceRepository.getInvoice(invoiceId);//invoice is selected
Order order = invoice.getOrder();
}
Here my order relation is not null but not initialized and not proxied, so If I call order.getOtherRelations it returns empty.
In case B I call something like:
public void create(){ //This method IS NOT Transactional
invoiceService.createInvoice();//This method is Transactional
waybillService.createWaybilFromInvoice();//The method declared above
}
I tried:
Make the create method Transactional
Set propagation to REQUIRES_NEW for createWaybillFromInvoice
Here are some logs:
2020-06-04 17:17:16.337 DEBUG 1208 --- [nio-9002-exec-4] o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [io.salesart.billingservice.service.impl.WaybillServiceImpl.createWayBillFromInvoice]:
2020-06-04 17:17:16.376 DEBUG 1208 --- [nio-9002-exec-4] o.s.jdbc.datasource.DataSourceUtils : Changing isolation level of JDBC Connection [HikariProxyConnection#2044564149 wrapping org.postgresql.jdbc.PgConnection#27db45f] to 2
2020-06-04 17:17:16.450 DEBUG 1208 --- [nio-9002-exec-4] o.h.e.t.internal.TransactionImpl : On TransactionImpl creation, JpaCompliance#isJpaTransactionComplianceEnabled == false
2020-06-04 17:17:16.451 DEBUG 1208 --- [nio-9002-exec-4] o.h.e.t.internal.TransactionImpl : begin
2020-06-04 17:17:16.451 DEBUG 1208 --- [nio-9002-exec-4] org.postgresql.jdbc.PgConnection : setAutoCommit = false
2020-06-04 17:17:16.457 DEBUG 1208 --- [nio-9002-exec-4] o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle#caf1ee0]
2020-06-04 17:17:19.532 DEBUG 1208 --- [nio-9002-exec-4] o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(1021250378<open>)] for JPA transaction

XAER_OUTSIDE Exception - Spring 4.0.3 - Hibernate 4.1.12 - JTA - Websphere 8 - DB2

EDIT - I have checked this combinations so it seems there's something wrong with Hibernate 4:
Spring 4 + JPA + Hibernate 4 -> Exception
Spring 4 + Hibernate 4 -> Exception
Spring 4 + JPA + Hibernate 3 -> OK
Spring 4 + Hibernate 3 -> OK
Spring 3 + JPA - Hibernate 4 -> Exception
Spring 3 + JPA - Hibernate 3 -> OK
Spring 3 + Hibernate 3 -> OK
I have recently upgraded an application from Spring 3.2/Hibernate 3.6.10 to Spring 4.0.3 + Hibernate 4.1.12. My environment is IBM Websphere 8.0.0.7 and DB2 and the application is configured to use a XA Datasource.
The point is that at the first database call (subsequent calls are always OK) I am getting this error:
#Transactional(readOnly = true)
public Foo loadFoo(int id) {
LOG.debug("load {}", id);
FooEntity fe = fooDAO.findOne(id);
...
}
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'fooRestController'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'globalControllerAdvice'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'org.springframework.transaction.interceptor.TransactionInterceptor#0'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'transactionManager'
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Invoking WebSphere UOW action: type=1, join=false
org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource DEBUG - Adding transactional method 'findOne' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'transactionManager'
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Invoking WebSphere UOW action: type=1, join=true
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Opening JPA EntityManager
org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl DEBUG - Skipping JTA sync registration due to auto join checking
org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl DEBUG - successfully registered Synchronization
org.hibernate.ejb.AbstractEntityManagerImpl DEBUG - Looking for a JTA transaction to join
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Registering transaction synchronization for JPA EntityManager
org.hibernate.loader.Loader DEBUG - Loading entity: [com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Obtaining JDBC connection
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Obtained JDBC connection
DSRA0304E: XAException occurred. XAException contents and details are: "".
DSRA0302E: XAException occurred. Error code is: XAER_OUTSIDE (-9). Exception is: XAER_OUTSIDE
J2CA0027E: An exception occurred while invoking start on an XA Resource Adapter from DataSource jdbc/LOCDBD1_XA, within transaction ID {XidImpl: formatId(57415344), gtrid_length(36), bqual_length(54),
data(0000014517a4c063000000015e7f81b4c90865e6b88e167905e5d2ed67f44ed6409cba5c0000014517a4c063000000015e7f81b4c90865e6b88e167905e5d2ed67f44ed6409cba5c000000010000000000000000000000000001)} : com.ibm.db2.jcc.c.zh: XAER_OUTSIDE
Caused by: javax.transaction.RollbackException: XAResource working outside transaction
at com.ibm.tx.jta.impl.RegisteredResources.startRes(RegisteredResources.java:1019)
at com.ibm.ws.tx.jta.RegisteredResources.enlistResource(RegisteredResources.java:1113)
at com.ibm.ws.tx.jta.TransactionImpl.enlistResource(TransactionImpl.java:2214)
at com.ibm.tx.jta.impl.EmbeddableTranManagerSet.enlist(EmbeddableTranManagerSet.java:150)
at com.ibm.ejs.j2c.XATransactionWrapper.enlist(XATransactionWrapper.java:727)
... 140 more
Caused by: com.ibm.db2.jcc.c.zh: XAER_OUTSIDE
at com.ibm.db2.jcc.b.bc.a(bc.java:1651)
at com.ibm.db2.jcc.b.bc.start(bc.java:1530)
at com.ibm.ws.rsadapter.spi.WSRdbXaResourceImpl.start(WSRdbXaResourceImpl.java:1525)
at com.ibm.ejs.j2c.XATransactionWrapper.start(XATransactionWrapper.java:1475)
at com.ibm.ws.Transaction.JTA.JTAResourceBase.start(JTAResourceBase.java:153)
at com.ibm.tx.jta.impl.RegisteredResources.startRes(RegisteredResources.java:1002)
... 144 more
This is the log trace of the second and successful call :
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'fooRestController'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'globalControllerAdvice'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'transactionManager'
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Invoking WebSphere UOW action: type=1, join=false
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'transactionManager'
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Invoking WebSphere UOW action: type=1, join=true
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Opening JPA EntityManager
org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl DEBUG - Skipping JTA sync registration due to auto join checking
org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl DEBUG - successfully registered Synchronization
org.hibernate.ejb.AbstractEntityManagerImpl DEBUG - Looking for a JTA transaction to join
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Registering transaction synchronization for JPA EntityManager
org.hibernate.loader.Loader DEBUG - Loading entity: [com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Obtaining JDBC connection
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Obtained JDBC connection
org.hibernate.loader.Loader DEBUG - Result set row: 0
org.hibernate.loader.Loader DEBUG - Result row: EntityKey[com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.internal.TwoPhaseLoad DEBUG - Resolving associations for [com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.internal.TwoPhaseLoad DEBUG - Done materializing entity [com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Releasing JDBC connection
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Released JDBC connection
org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler DEBUG - HHH000163: Logical connection releasing its physical connection
org.hibernate.loader.Loader DEBUG - Done entity load
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Returned from WebSphere UOW action: type=1, join=true
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Closing JPA EntityManager
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Aggressively releasing JDBC connection
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Returned from WebSphere UOW action: type=1, join=false
The relevant part of my cfg is:
<bean id="mainEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="mainPersistenceUnit"/>
<property name="jtaDataSource" ref="mainDataSource"/>
<property name="packagesToScan" ref="packages-mainEntityManagerFactory"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.transaction.jta.platform">org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform</prop>
<prop key="hibernate.current_session_context_class">jta</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory</prop>
</props>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
</bean>
<tx:annotation-driven order="0" />
<bean name="transactionManager" class="org.springframework.transaction.jta.WebSphereUowTransactionManager">
<property name="allowCustomIsolationLevels" value="true" />
</bean>
Any idea why it fails the first time it's called?
The problem solved by itself upgrading to Spring 4.1.6 and Hibernate 4.2.19. I guess it was a Hibernate-related issue.

Sharing transaction with AbstractRoutingDataSource

I've a problem very close to this one Sharing a transaction while using AbstractRoutingDataSource to switch datasources but I'm not able to solve using the accepted answer. I've a transactional method who have to write the same entity into two different datasource in transactional mode. When transaction commit I've a
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (VETO_PROD.SYS_C0013988) violated
This is my Transalctional method:
#Override
#Transactional(propagation = Propagation.REQUIRES_NEW)
public ContactTypeJson definisciNuovaContactType(String descrizione) throws Exception {
String functionCode = RandomStringUtils.randomAlphanumeric(5).toUpperCase();
LOGGER.debug("Ho generato la functionCode[" + functionCode + "]");
while (!isContactTypeAvailable(functionCode) || !notificatorService.isFunctionCodeAvailable(functionCode)) {
LOGGER.debug("La functionCode[" + functionCode + "] e' gia' in utilizzo, genero una nuova...");
functionCode = RandomStringUtils.randomAlphanumeric(5).toUpperCase();
LOGGER.debug("...la nuova functionCode generata e' [" + functionCode + "]");
}
ContactType contactType = new ContactType();
contactType.setName(functionCode);
contactType.setDescription(descrizione);
notificatorService.insertNewFunction(functionCode, descrizione);
entityManagerFRVP0.flush();
entityManagerFRVP0.clear();
VetrinaContextHolder.setTargetDataSource(VetrinaToolConstants.FRVP_DATASOURCE);
entityManagerFRVP0.persist(contactType);
entityManagerFRVP0.flush();
entityManagerFRVP0.clear();
VetrinaContextHolder.setTargetDataSource(VetrinaToolConstants.PWVP_DATASOURCE);
ContactType contactType1 = new ContactType();
contactType1.setName(functionCode);
contactType1.setDescription(descrizione);
entityManagerFRVP0.persist(contactType1);
VetrinaContextHolder.clearTargetDataSource();
ContactTypeToJsonConverter converter = new ContactTypeToJsonConverter();
return converter.convert(contactType);
}
This is the JPA log:
2013-07-15 10:47:59,570 DEBUG [sql] 2013-07-15 10:47:59.569--ServerSession(26361419)--Connection(16434777)--Thread(Thread[[ACTIVE] ExecuteThread: '18' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--SELECT VET_SEQ_CONTACT_TYPE.NEXTVAL FROM DUAL
2013-07-15 10:47:59,581 DEBUG [sql] 2013-07-15 10:47:59.58--ClientSession(21299255)--Connection(17900213)--Thread(Thread[[ACTIVE] ExecuteThread: '18' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--INSERT INTO S_VET_CONTACT_TYPE (ID, DESCRIPTION, NAME, FASEDIDEFAULT_ID) VALUES (81, Prova doppione, 16XOV, NULL)
2013-07-15 10:47:59,596 DEBUG [sql] 2013-07-15 10:47:59.595--ClientSession(21299255)--Connection(17900213)--Thread(Thread[[ACTIVE] ExecuteThread: '18' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--SELECT VET_SEQ_CONTACT_TYPE.NEXTVAL FROM DUAL
2013-07-15 10:47:59,601 DEBUG [sql] 2013-07-15 10:47:59.6--ClientSession(21299255)--Connection(17900213)--Thread(Thread[[ACTIVE] ExecuteThread: '18' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--INSERT INTO S_VET_CONTACT_TYPE (ID, DESCRIPTION, NAME, FASEDIDEFAULT_ID) VALUES (82, Prova doppione, 16XOV, NULL)
This the stack:
2013-07-15 10:47:59,421 DEBUG [WebLogicJtaTransactionManager] Creating new transaction with name [com.intesasanpaolo.frvp0.alten.vetrinatool.service.console.ConsoleServiceImpl.definisciNuovaContactType]: PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT; ''
2013-07-15 10:47:59,430 DEBUG [EntityManagerFactoryUtils] Opening JPA EntityManager
2013-07-15 10:47:59,430 DEBUG [EntityManagerFactoryUtils] Registering transaction synchronization for JPA EntityManager
2013-07-15 10:47:59,483 DEBUG [TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource] Adding transactional method 'findOne' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
2013-07-15 10:47:59,483 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager'
2013-07-15 10:47:59,483 DEBUG [WebLogicJtaTransactionManager] Participating in existing transaction
2013-07-15 10:47:59,483 DEBUG [EntityManagerFactoryUtils] Opening JPA EntityManager
2013-07-15 10:47:59,483 DEBUG [EntityManagerFactoryUtils] Registering transaction synchronization for JPA EntityManager
2013-07-15 10:47:59,542 DEBUG [AnnotationTransactionAttributeSource] Adding transactional method 'insertNewFunction' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2013-07-15 10:47:59,543 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager'
2013-07-15 10:47:59,543 DEBUG [WebLogicJtaTransactionManager] Participating in existing transaction
2013-07-15 10:47:59,543 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager'
2013-07-15 10:47:59,543 DEBUG [WebLogicJtaTransactionManager] Participating in existing transaction
2013-07-15 10:47:59,549 DEBUG [TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource] Adding transactional method 'save' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2013-07-15 10:47:59,549 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager'
2013-07-15 10:47:59,550 DEBUG [WebLogicJtaTransactionManager] Participating in existing transaction
2013-07-15 10:47:59,600 DEBUG [EntityManagerFactoryUtils] Closing JPA EntityManager
2013-07-15 10:47:59,600 DEBUG [EntityManagerFactoryUtils] Closing JPA EntityManager
2013-07-15 10:47:59,600 DEBUG [WebLogicJtaTransactionManager] Initiating transaction commit
2013-07-15 10:47:59,827 DEBUG [DispatcherServlet] Handler execution resulted in exception - forwarding to resolved error view: ModelAndView: reference to view with name 'jsonView'; model is {hasErrors=true, errorCode=GEN_EX, errorMessages=Errore generico}
org.springframework.transaction.UnexpectedRollbackException: JTA transaction unexpectedly rolled back (maybe due to a timeout); nested exception is weblogic.transaction.RollbackException: Unexpected exception in beforeCompletion: sync=org.eclipse.persistence.transaction.JTASynchronizationListener#2f0af4
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (VETO_PROD.SYS_C0013988) violated
Error Code: 1
Call: INSERT INTO S_VET_CONTACT_TYPE (ID, DESCRIPTION, NAME, FASEDIDEFAULT_ID) VALUES (82, 'Prova doppione', '16XOV', NULL)
Query: InsertObjectQuery(ContactType [id=82, name=16XOV, description=Prova doppione, fasiAssociate={[]}, faseDiDefault=null])
at org.springframework.transaction.jta.JtaTransactionManager.doCommit(JtaTransactionManager.java:1014)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:755)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:724)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:387)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy310.definisciNuovaContactType(Unknown Source)
at com.intesasanpaolo.frvp0.alten.vetrinatool.mvc.console.controller.CreaContactTypeController.creaNuovaContactType(CreaContactTypeController.java:30)
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)
I'm using WebLogic 10.3.5 with XA datasources and org.springframework.transaction.jta.WebLogicJtaTransactionManager
Any idea?
You are violating a unique constraint. I assume you have one defined on the Contact name, so you cannot insert two contacts with the same name.
Trying to switch the connection under a DataSource on the fly seems like a very, very, bad idea. Instead you should have two persistence units, one going to one database, and one going to the other.
You may also want to investigate EclipseLink's data partitioning, or composite persistence units.
http://wiki.eclipse.org/EclipseLink/Examples/JPA/Partitioning
http://wiki.eclipse.org/EclipseLink/Examples/JPA/Composite

SimpleJdbcCall works calling n-times StoredProcedure then throws error

I've the next error:
[http-thread-pool-8080(5)] DEBUG o.s.jdbc.core.simple.SimpleJdbcCall - JdbcCall call not compiled before execution - invoking compile
[http-thread-pool-8080(5)] DEBUG o.s.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
[http-thread-pool-8080(5)] DEBUG o.s.jdbc.datasource.DataSourceUtils - Registering transaction synchronization for JDBC Connection
[http-thread-pool-8080(5)] DEBUG o.s.j.c.m.CallMetaDataProviderFactory - Using org.springframework.jdbc.core.metadata.SqlServerCallMetaDataProvider
[http-thread-pool-8080(5)] DEBUG o.s.j.c.m.CallMetaDataProvider - Retrieving metadata for BATABASE/dbo/PA_INSERT
[http-thread-pool-8080(5)] WARN o.s.j.c.m.CallMetaDataProvider - Error while retrieving metadata for procedure columns: com.microsoft.sqlserver.jdbc.SQLServerException: Could not find prepared statement with handle 41.
[http-thread-pool-8080(5)] DEBUG o.s.jdbc.core.simple.SimpleJdbcCall - Compiled stored procedure. Call string is [{call DATABASE.dbo.PA_INSERT()}]
[http-thread-pool-8080(5)] DEBUG o.s.jdbc.core.simple.SimpleJdbcCall - SqlCall for procedure [PA_ISolicitudDistincion] compiled
[http-thread-pool-8080(5)] DEBUG o.s.j.c.m.CallMetaDataContext - Matching [COLUMN1, COLUMN2, COLUMN3] with []
[http-thread-pool-8080(5)] DEBUG o.s.j.c.m.CallMetaDataContext - Found match for []
[http-thread-pool-8080(5)] DEBUG o.s.jdbc.core.simple.SimpleJdbcCall - The following parameters are used for call {call DATABASE.dbo.PA_INSERT()} with: {}
[http-thread-pool-8080(5)] DEBUG o.s.jdbc.core.JdbcTemplate - Calling stored procedure [{call DATABASE.dbo.PA_INSERT()}]
[http-thread-pool-8080(5)] INFO o.s.b.f.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
[http-thread-pool-8080(5)] INFO o.s.j.support.SQLErrorCodesFactory - SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase]
[http-thread-pool-8080(5)] DEBUG o.s.j.support.SQLErrorCodesFactory - Looking up default SQLErrorCodes for DataSource [com.sun.gjc.spi.jdbc40.DataSource40#12ea240]
[http-thread-pool-8080(5)] DEBUG o.s.j.support.SQLErrorCodesFactory - Database product name cached for DataSource [com.sun.gjc.spi.jdbc40.DataSource40#12ea240]: name is 'Microsoft SQL Server'
[http-thread-pool-8080(5)] DEBUG o.s.j.support.SQLErrorCodesFactory - SQL error codes for 'Microsoft SQL Server' found
[http-thread-pool-8080(5)] DEBUG o.s.j.s.SQLErrorCodeSQLExceptionTranslator - Unable to translate SQLException with Error code '201', will now try the fallback translator
[http-thread-pool-8080(5)] DEBUG o.s.j.s.SQLStateSQLExceptionTranslator - Extracted SQL state class 'S0' from value 'S0004'
[http-thread-pool-8080(5)] DEBUG o.s.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
But, it's strange, because, the same SP works without errors, but when is called N-times throws the error.
I'm using Spring with a pooled connection through Glassfish 3.1.2. to a Sqlserver 2005 database.
Here is the java function
public int registrar(Object1 p,
Object2 d)
{
try
{
final SimpleJdbcCall jdbcCall = (SimpleJdbcCall) context
.getBean("insert");
jdbcCall.setCatalogName("DATABASE");
jdbcCall.setSchemaName("dbo");
final MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("COLUMN1", p.get1());
params.addValue("COLUMN2", p.get1());
params.addValue("COLUMN3", d.get2());
final Map<String, Object> execute = jdbcCall.execute(params);
return (Integer) execute.get("IDENTITY");
}
catch (DataAccessException e)
{
return null;
}
}
It looks like that you are sharing your "insert" - bean among threads. Try using scope="prototype" on your insert bean, so you make sure that you are getting a new instance for each call.

Spring 3.1.1 service not lazy loading joined custom objects

I'm getting an odd error when calling a service.
It won't load the user object into the card pojo.
The error is displayed on the user attribute in my card pojo (Viewing through eclipse debug mode).
com.sun.jdi.InvocationException occurred invoking method.
The resulting error then occurs when attempting to render the view:
SEVERE: Servlet.service() for servlet [WebApp] in context with path [/WebApp] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "user.card.alias" (card/index:37)] with root cause
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
#Controller
public class CardController extends AppController
{
static Logger logger = LoggerFactory.getLogger(CardController.class);
#Autowired
private ICardService cardService;
// Card home page (list all cards and options)
#RequestMapping(value = "/card", method = RequestMethod.GET)
public String cardMain(Model model, HttpServletRequest request)
{
PagedListHolder<Card> cards = new PagedListHolder<Card>(
cardService.getAll());
...
}
...
}
#Service
public class CardService implements ICardService
{
#Autowired
ICardDAO cardDAO;
#Transactional
public List<Card> getAll()
{
return cardDAO.findAll();
}
...
}
#Entity
public class Card implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumns({ #JoinColumn(name = "USERID", referencedColumnName = "ID") })
#Valid
private User user;
public User getUser()
{
if (user == null)
{
user = new User();
}
return user;
}
public void setUser(User user)
{
this.user = user;
}
...
}
#Entity
public class User implements Serializable
{
#OneToOne(mappedBy="user", cascade={CascadeType.ALL})
private UserRole userRole;
#OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = { CascadeType.ALL })
private Set<Card> cards;
public UserRole getUserRole()
{
if (userRole == null)
{
userRole = new UserRole();
}
return userRole;
}
public void setUserRole(UserRole userRole)
{
this.userRole = userRole;
}
public Set<Card> getCards()
{
if (cards == null)
{
cards = new LinkedHashSet<Card>();
}
return cards;
}
public void setCards(Set<Card> cards)
{
this.cards = cards;
}
...
}
I have logging enabled and it looks like it does get them at some point (user=com.webapp.model.User#35, pan=5499999999999999, expiry=1214....):
2012-08-30 00:15:47,212 DEBUG [http-bio-8080-exec-4] o.s.b.f.s.DefaultListableBeanFactory [AbstractBeanFactory.java:245] Returning cached instance of singleton bean 'transactionManager'
2012-08-30 00:15:47,214 DEBUG [http-bio-8080-exec-4] o.s.o.j.JpaTransactionManager [AbstractPlatformTransactionManager.java:365] Creating new transaction with name [com.webapp.service.impl.CardService.getAll]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2012-08-30 00:15:47,215 DEBUG [http-bio-8080-exec-4] o.h.i.SessionImpl [SessionImpl.java:265] opened session at timestamp: 13462821472
2012-08-30 00:15:47,216 DEBUG [http-bio-8080-exec-4] o.s.o.j.JpaTransactionManager [JpaTransactionManager.java:368] Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl#d49865b] for JPA transaction
2012-08-30 00:15:47,216 DEBUG [http-bio-8080-exec-4] o.h.t.JDBCTransaction [JDBCTransaction.java:78] begin
2012-08-30 00:15:47,217 DEBUG [http-bio-8080-exec-4] o.h.j.ConnectionManager [ConnectionManager.java:444] opening JDBC connection
2012-08-30 00:15:47,217 DEBUG [http-bio-8080-exec-4] o.s.j.d.DriverManagerDataSource [DriverManagerDataSource.java:162] Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/Thesis]
2012-08-30 00:15:47,288 DEBUG [http-bio-8080-exec-4] o.h.t.JDBCTransaction [JDBCTransaction.java:83] current autocommit status: true
2012-08-30 00:15:47,289 DEBUG [http-bio-8080-exec-4] o.h.t.JDBCTransaction [JDBCTransaction.java:86] disabling autocommit
2012-08-30 00:15:47,290 DEBUG [http-bio-8080-exec-4] o.s.o.j.JpaTransactionManager [JpaTransactionManager.java:400] Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle#296fb592]
2012-08-30 00:15:47,292 DEBUG [http-bio-8080-exec-4] o.h.j.AbstractBatcher [AbstractBatcher.java:410] about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
2012-08-30 00:15:47,293 DEBUG [http-bio-8080-exec-4] o.h.SQL [SQLStatementLogger.java:111] select card0_.id as id6_, card0_.active as active6_, card0_.alias as alias6_, card0_.cvc as cvc6_, card0_.expiry as expiry6_, card0_.pan as pan6_, card0_.USERID as USERID6_ from Card card0_
2012-08-30 00:15:47,297 DEBUG [http-bio-8080-exec-4] o.h.j.AbstractBatcher [AbstractBatcher.java:426] about to open ResultSet (open ResultSets: 0, globally: 0)
2012-08-30 00:15:47,300 DEBUG [http-bio-8080-exec-4] o.h.l.Loader [Loader.java:1322] result row: EntityKey[com.webapp.model.Card#1]
2012-08-30 00:15:47,301 DEBUG [http-bio-8080-exec-4] o.h.l.Loader [Loader.java:1322] result row: EntityKey[com.webapp.model.Card#2]
2012-08-30 00:15:47,303 DEBUG [http-bio-8080-exec-4] o.h.l.Loader [Loader.java:1322] result row: EntityKey[com.webapp.model.Card#3]
2012-08-30 00:15:47,317 DEBUG [http-bio-8080-exec-4] o.h.j.AbstractBatcher [AbstractBatcher.java:433] about to close ResultSet (open ResultSets: 1, globally: 1)
2012-08-30 00:15:47,317 DEBUG [http-bio-8080-exec-4] o.h.j.AbstractBatcher [AbstractBatcher.java:418] about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
2012-08-30 00:15:47,318 DEBUG [http-bio-8080-exec-4] o.h.e.TwoPhaseLoad [TwoPhaseLoad.java:130] resolving associations for [com.webapp.model.Card#1]
2012-08-30 00:15:47,319 DEBUG [http-bio-8080-exec-4] o.h.e.TwoPhaseLoad [TwoPhaseLoad.java:255] done materializing entity [com.webapp.model.Card#1]
2012-08-30 00:15:47,320 DEBUG [http-bio-8080-exec-4] o.h.e.TwoPhaseLoad [TwoPhaseLoad.java:130] resolving associations for [com.webapp.model.Card#2]
2012-08-30 00:15:47,321 DEBUG [http-bio-8080-exec-4] o.h.e.TwoPhaseLoad [TwoPhaseLoad.java:255] done materializing entity [com.webapp.model.Card#2]
2012-08-30 00:15:47,322 DEBUG [http-bio-8080-exec-4] o.h.e.TwoPhaseLoad [TwoPhaseLoad.java:130] resolving associations for [com.webapp.model.Card#3]
2012-08-30 00:15:47,323 DEBUG [http-bio-8080-exec-4] o.h.e.TwoPhaseLoad [TwoPhaseLoad.java:255] done materializing entity [com.webapp.model.Card#3]
2012-08-30 00:15:47,339 DEBUG [http-bio-8080-exec-4] o.h.e.StatefulPersistenceContext [StatefulPersistenceContext.java:893] initializing non-lazy collections
2012-08-30 00:15:47,339 TRACE [http-bio-8080-exec-4] o.s.o.j.JpaTransactionManager [AbstractPlatformTransactionManager.java:922] Triggering beforeCommit synchronization
2012-08-30 00:15:47,340 TRACE [http-bio-8080-exec-4] o.s.o.j.JpaTransactionManager [AbstractPlatformTransactionManager.java:935] Triggering beforeCompletion synchronization
2012-08-30 00:15:47,341 DEBUG [http-bio-8080-exec-4] o.s.o.j.JpaTransactionManager [AbstractPlatformTransactionManager.java:752] Initiating transaction commit
2012-08-30 00:15:47,341 DEBUG [http-bio-8080-exec-4] o.s.o.j.JpaTransactionManager [JpaTransactionManager.java:507] Committing JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl#d49865b]
2012-08-30 00:15:47,342 DEBUG [http-bio-8080-exec-4] o.h.t.JDBCTransaction [JDBCTransaction.java:130] commit
2012-08-30 00:15:47,342 DEBUG [http-bio-8080-exec-4] o.h.e.d.AbstractFlushingEventListener [AbstractFlushingEventListener.java:134] processing flush-time cascades
2012-08-30 00:15:47,345 DEBUG [http-bio-8080-exec-4] o.h.e.d.AbstractFlushingEventListener [AbstractFlushingEventListener.java:177] dirty checking collections
2012-08-30 00:15:47,347 DEBUG [http-bio-8080-exec-4] o.h.e.d.AbstractFlushingEventListener [AbstractFlushingEventListener.java:108] Flushed: 0 insertions, 0 updates, 0 deletions to 12 objects
2012-08-30 00:15:47,348 DEBUG [http-bio-8080-exec-4] o.h.e.d.AbstractFlushingEventListener [AbstractFlushingEventListener.java:114] Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
2012-08-30 00:15:47,349 DEBUG [http-bio-8080-exec-4] o.h.p.Printer [Printer.java:106] listing entities:
2012-08-30 00:15:47,354 DEBUG [http-bio-8080-exec-4] o.h.p.Printer [Printer.java:113] com.webapp.model.Card{id=2, alias=sadsdsdf, cvc=111, active=true, user=com.webapp.model.User#35, pan=5499999999999999, expiry=1214}
2012-08-30 00:15:47,355 DEBUG [http-bio-8080-exec-4] o.h.p.Printer [Printer.java:113] com.webapp.model.Card{id=3, alias=asdsdsdfsdf, cvc=122, active=false, user=com.webapp.model.User#47, pan=5411222222222222, expiry=1214}
2012-08-30 00:15:47,358 DEBUG [http-bio-8080-exec-4] o.h.p.Printer [Printer.java:113] com.webapp.model.Card{id=1, alias=sdfsdfsdfd, cvc=111, active=true, user=com.webapp.model.User#35, pan=5411111111111111, expiry=1214}
2012-08-30 00:15:47,361 DEBUG [http-bio-8080-exec-4] o.h.t.JDBCTransaction [JDBCTransaction.java:223] re-enabling autocommit
2012-08-30 00:15:47,363 DEBUG [http-bio-8080-exec-4] o.h.t.JDBCTransaction [JDBCTransaction.java:143] committed JDBC Connection
2012-08-30 00:15:47,363 DEBUG [http-bio-8080-exec-4] o.h.j.ConnectionManager [ConnectionManager.java:427] aggressively releasing JDBC connection
2012-08-30 00:15:47,364 DEBUG [http-bio-8080-exec-4] o.h.j.ConnectionManager [ConnectionManager.java:464] releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
2012-08-30 00:15:47,365 TRACE [http-bio-8080-exec-4] o.s.o.j.JpaTransactionManager [AbstractPlatformTransactionManager.java:948] Triggering afterCommit synchronization
2012-08-30 00:15:47,365 TRACE [http-bio-8080-exec-4] o.s.o.j.JpaTransactionManager [AbstractPlatformTransactionManager.java:964] Triggering afterCompletion synchronization
2012-08-30 00:15:47,366 DEBUG [http-bio-8080-exec-4] o.s.o.j.JpaTransactionManager [JpaTransactionManager.java:593] Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl#d49865b] after transaction
2012-08-30 00:15:47,367 DEBUG [http-bio-8080-exec-4] o.s.o.j.EntityManagerFactoryUtils [EntityManagerFactoryUtils.java:343] Closing JPA EntityManager
Any suggestions as to the cause of this error?
I'm using Spring 3.1.1.RELEASE by the way.
I have the same problem, and the reason is thymeleaf, after load the objects, close the database session, as stated by #garis-m-suero on my own post.
By now, this is the way thymeleaf view works, and quoting Mr. #garis-m-suero
you probably can make the scope of the model in spring to be session, but that is not worth it
EDIT:
Another option, that seems to work really fine for me is setting the OpenSessionInViewInterceptor on your configuration like this:
#Bean
public OpenSessionInViewInterceptor openSessionInViewInterceptor(){
OpenSessionInViewInterceptor openSessionInterceptor = new OpenSessionInViewInterceptor();
openSessionInterceptor.setSessionFactory(sessionFactory);
return openSessionInterceptor;
}
and them overriding the addInterceptor with this:
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(thymeleafLayoutInterceptor());
registry.addInterceptor(applicationInterceptor());
registry.addWebRequestInterceptor(openSessionInViewInterceptor());
}
Found this solution on github

Resources