Connection not releasing for StoredProcedureQuery without #Transactional - jpa

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.

Related

Hibernate not updating schema automatically

I am using SpringBoot with Hibernate. I have 2 Postgres datasources. I have an existing database (pims) and a new database (powwow), and some entities. When I start up SpringBoot, I would like it to automatically create the tables in the new powwow database, however it is not doing so.
application.properties
# pims datasource
spring.datasource1.driver-class-name=org.postgresql.Driver
spring.datasource1.jdbc-url=jdbc:postgresql://localhost:5432/pims
spring.datasource1.username=postgres
spring.datasource1.password=postgres
# powwow datasource
spring.datasource2.driver-class-name=org.postgresql.Driver
spring.datasource2.jdbc-url=jdbc:postgresql://localhost:5432/powwow
spring.datasource2.username=postgres
spring.datasource2.password=postgres
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.database-platform=postgres
spring.jpa.hibernate.ddl-auto=update
#spring.jpa.properties.hibernate.hbm2ddl.auto=update
#spring.jpa.generate-ddl=true
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource2.dbcp2.test-while-idle=true
spring.datasource2.dbcp2.validation-query=select 1
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
# logging
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
Example entity:
PowWowActivityEntity.java
#Entity
#Table(name = "powwowactivity")
public class PowWowActivityEntity {
#Id
#Column(name = "activity_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long activity_id;
#Column(name = "status")
private String status;
Output
2022-08-16 09:19:13.227 INFO 65945 --- [ main] com.clubtravel.powwow.PowWowApplication : Started PowWowApplication in 11.544 seconds (JVM running for 12.617)
2022-08-16 09:19:13.255 DEBUG 65945 --- [ scheduling-1] org.hibernate.SQL : select count(*) as col_0_0_ from powwowglaccountmapping powwowglac0_
2022-08-16 09:19:13.269 DEBUG 65945 --- [ Async-1] org.hibernate.SQL : insert into powwowactivity (comment, create_date, status, user_name) values (?, ?, ?, ?)
2022-08-16 09:19:13.272 TRACE 65945 --- [ Async-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [Server started on HOST: Richards-MacBook-Pro.local.]
2022-08-16 09:19:13.273 TRACE 65945 --- [ Async-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [TIMESTAMP] - [Tue Aug 16 09:19:13 SAST 2022]
2022-08-16 09:19:13.274 TRACE 65945 --- [ Async-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [VARCHAR] - [Info]
2022-08-16 09:19:13.274 TRACE 65945 --- [ Async-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [VARCHAR] - [system]
2022-08-16 09:19:13.281 WARN 65945 --- [ Async-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42P01
2022-08-16 09:19:13.281 ERROR 65945 --- [ Async-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: relation "powwowactivity" does not exist
Question
I thought by adding the following line, the new tables would automatically be created by updating the schema. Any ideas? Is this not working because I have more than one datasource?
spring.jpa.hibernate.ddl-auto=update
The reason it was not working is because i have 2 datasources defined. If i change the config to update, it works (properties.put("hibernate.hbm2ddl.auto", "update");):
#Bean(name = "powwowEntityManager")
#Primary
public LocalContainerEntityManagerFactoryBean powwowEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(powwowDataSource());
em.setPackagesToScan(new String[] { "com.clubtravel.powwow.entities.powwow" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
// properties.put("hibernate.hbm2ddl.auto",env.getProperty("hibernate.hbm2ddl.auto"));
// properties.put("hibernate.dialect",env.getProperty("hibernate.dialect"));
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
em.setJpaPropertyMap(properties);
logger.info("Setting spring.datasource2 (powwowEntityManager) hibernate.hbm2ddl.auto = "+env.getProperty("hibernate.hbm2ddl.auto")+" and hibernate.dialect = "+env.getProperty("hibernate.dialect"));
return em;
}

My execution halts while implemented the Data Driven Approach

I have included few lines of code for data driven, where I will fetch the details from a Excel sheet and it will pass to the script in Run Time. Here my script won't execute and it hangs after returning the message in Eclipse Console:
Returning cached instance of singleton bean 'todoClient1'
Below attached the Code and package com.consol.citrus.integration.Demo.
import java.util.Hashtable;
import org.apache.log4j.helpers.SyslogWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ImportResource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.testng.SkipException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import com.consol.citrus.TestCaseMetaInfo.Status;
import com.consol.citrus.annotations.CitrusTest;
import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;
import com.consol.citrus.http.client.HttpClient;
import com.consol.citrus.message.MessageType;
public class UnSuccessFullLogin extends TestNGCitrusTestDesigner {
#Autowired (required=true)
#Qualifier("todoClient1")
private HttpClient todoClient1;
public Xls_Reader xls=new Xls_Reader(Constants.DATA_XLS_PATH);
String testCaseName="UnSuccessFullLogin";
public String actualResult="";
#CitrusTest
#Test(dataProvider="getData")
public void TestPost(Hashtable<String, String> data) {
echo("i am entered");
variable("Uname", "admin2");
variable("Pwd", "admin");
if(!DataUtil.isTestExecutable(xls, testCaseName) || data.get(Constants.RUNMODE_COL).equals("N")){
throw new SkipException("Skipping the test as Rnumode is N");
}
http()
.client(todoClient1)
.send()
.post("/rest/api/user/login")
.contentType("application/json")
// .payload("{ \"userName\": \"${uN}\", \"password\": \"${pwd}\"}");
.payload("{ \"userName\": \"${Uname}\", \"password\": \"${Pwd}\"}");
http()
.client(todoClient1)
.receive()
.response(HttpStatus.ACCEPTED)
.validate("$.statusCode", "400");
}
#DataProvider
public Object[][] getData()
{
return DataUtil.getData(xls, testCaseName);
}
}
Log Here:
17:37:56,650 DEBUG tListableBeanFactory| Creating shared instance of singleton bean 'todoClient'
17:37:56,650 DEBUG tListableBeanFactory| Creating instance of bean 'todoClient'
17:37:56,651 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'todoClientConfiguration'
17:37:56,675 DEBUG tListableBeanFactory| Eagerly caching bean 'todoClient' to allow for resolving potential circular references
17:37:56,690 DEBUG tListableBeanFactory| Finished creating instance of bean 'todoClient'
17:37:56,690 DEBUG tListableBeanFactory| Creating shared instance of singleton bean 'todoClient1Configuration'
17:37:56,690 DEBUG tListableBeanFactory| Creating instance of bean 'todoClient1Configuration'
17:37:56,691 DEBUG tListableBeanFactory| Eagerly caching bean 'todoClient1Configuration' to allow for resolving potential circular references
17:37:56,697 DEBUG tListableBeanFactory| Finished creating instance of bean 'todoClient1Configuration'
17:37:56,697 DEBUG tListableBeanFactory| Creating shared instance of singleton bean 'todoClient1'
17:37:56,697 DEBUG tListableBeanFactory| Creating instance of bean 'todoClient1'
17:37:56,697 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'todoClient1Configuration'
17:37:56,699 DEBUG tListableBeanFactory| Eagerly caching bean 'todoClient1' to allow for resolving potential circular references
17:37:56,699 DEBUG tListableBeanFactory| Finished creating instance of bean 'todoClient1'
17:37:56,699 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'globalVariables'
17:37:56,699 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'com.consol.citrus.report.MessageTracingTestListener#1'
17:37:56,700 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
17:37:56,851 DEBUG icApplicationContext| Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor#655a5d9c]
17:37:56,852 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'lifecycleProcessor'
17:37:56,856 DEBUG rcesPropertyResolver| Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
17:37:56,866 DEBUG ontextLoaderDelegate| Storing ApplicationContext in cache under key [[MergedContextConfiguration#7bd7d6d6 testClass = UnSuccessFullLogin, locations = '{}', classes = '{class com.consol.citrus.config.CitrusSpringConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
17:37:56,866 DEBUG context.cache| Spring test ApplicationContext cache statistics: [DefaultContextCache#1a6f2363 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 0, missCount = 1]
17:37:56,939 DEBUG on.InjectionMetadata| Processing injected element of bean 'com.consol.citrus.integration.Demo.UnSuccessFullLogin': AutowiredFieldElement for private com.consol.citrus.http.client.HttpClient com.consol.citrus.integration.Demo.UnSuccessFullLogin.todoClient1
17:37:56,942 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'todoClient1'
17:37:56,942 DEBUG ionBeanPostProcessor| Autowiring by type from bean name 'com.consol.citrus.integration.Demo.UnSuccessFullLogin' to bean named 'todoClient1'
17:37:56,947 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'testSuiteListeners'
17:37:56,947 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'testContextFactory'
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus - ------------------------------------------------------------------------
5876 [main] INFO com.consol.citrus.Citrus - .__ __
5876 [main] INFO com.consol.citrus.Citrus - ____ |__|/ |________ __ __ ______
5876 [main] INFO com.consol.citrus.Citrus - _/ ___\| \ __\_ __ \ | \/ ___/
5876 [main] INFO com.consol.citrus.Citrus - \ \___| || | | | \/ | /\___ \
5876 [main] INFO com.consol.citrus.Citrus - \___ >__||__| |__| |____//____ >
5876 [main] INFO com.consol.citrus.Citrus - \/ \/
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus - C I T R U S T E S T S 2.7.2
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus - ------------------------------------------------------------------------
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus -
5876 [main] INFO com.consol.citrus.Citrus - BEFORE TEST SUITE: SUCCESS
5876 [main] INFO com.consol.citrus.Citrus - ------------------------------------------------------------------------
5876 [main] INFO com.consol.citrus.Citrus -
17:37:56,974 DEBUG estExecutionListener| Before test class: context [DefaultTestContext#740fb309 testClass = UnSuccessFullLogin, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#7bd7d6d6 testClass = UnSuccessFullLogin, locations = '{}', classes = '{class com.consol.citrus.config.CitrusSpringConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null].
17:37:56,975 DEBUG estExecutionListener| Performing dependency injection for test context [[DefaultTestContext#740fb309 testClass = UnSuccessFullLogin, testInstance = com.consol.citrus.integration.Demo.UnSuccessFullLogin#5524cca1, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#7bd7d6d6 testClass = UnSuccessFullLogin, locations = '{}', classes = '{class com.consol.citrus.config.CitrusSpringConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]].
17:37:56,975 DEBUG ontextLoaderDelegate| Retrieved ApplicationContext from cache with key [[MergedContextConfiguration#7bd7d6d6 testClass = UnSuccessFullLogin, locations = '{}', classes = '{class com.consol.citrus.config.CitrusSpringConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
17:37:56,975 DEBUG context.cache| Spring test ApplicationContext cache statistics: [DefaultContextCache#1a6f2363 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 1, missCount = 1]
17:37:56,976 DEBUG on.InjectionMetadata| Processing injected element of bean 'com.consol.citrus.integration.Demo.UnSuccessFullLogin': AutowiredFieldElement for private com.consol.citrus.http.client.HttpClient com.consol.citrus.integration.Demo.UnSuccessFullLogin.todoClient1
17:37:56,976 DEBUG tListableBeanFactory| Returning cached instance of singleton bean 'todoClient1'
Please see the following working sample how to use TestNG data provider with Citrus:
public class DataProviderJavaIT extends TestNGCitrusTestDesigner {
#CitrusTest
#CitrusParameters( {"message", "delay"} )
#Test(dataProvider = "sampleDataProvider")
public void dataProvider(String message, Long sleep) {
echo(message);
sleep(sleep);
echo("${message}");
echo("${delay}");
}
#DataProvider
public Object[][] sampleDataProvider() {
return new Object[][] {
{ "Hello World!", 300L },
{ "Hallo Welt!", 1000L },
{ "Hallo Citrus!", 500L },
};
}
}
According to the sample you are missing the #CitrusParameters annotation that translates data provider arguments to Citrus test variables.

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

Why doesn't JPA's FetchType.LAZY work?

JPA provider eclipselink 2.3
AS glassfish 3.1.1 B12
Binary protocol for remote invocation Hessian
Server side ejb+jpa
Client side Plain Swing .
JPA mappings
#Entity
#Table(name = "FATHER", catalog = "CAT", schema = "dbo")
public class Father implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(generator = "FATHERUID", strategy = GenerationType.TABLE)
#TableGenerator(name = "FATHERUID", table = "FAMILY_UID", catalog = "LSDB", schema = "dbo", pkColumnName = "PRIM", pkColumnValue = "father_uid", valueColumnName = "UID", allocationSize = 1, initialValue = 0)
private Long id;
#OneToOne(mappedBy = "father", fetch = FetchType.LAZY)
private Mother mother;
#OneToMany(mappedBy = "father", fetch = FetchType.LAZY)
private List<Friend> friendList;
}
#Entity
#Table(name = "FRIEND", catalog = "CAT", schema = "dbo")
#NamedQueries({
#NamedQuery(name = "Friend.findAll", query = "SELECT f FROM Friend f")})
public class Friend implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(generator = "FRIENDUID", strategy = GenerationType.TABLE)
#TableGenerator(name = "FRIENDUID", table = "FAMILY_UID", catalog = "LSDB", schema = "dbo", pkColumnName = "PRIM", pkColumnValue = "friend_uid", valueColumnName = "UID", allocationSize = 1, initialValue = 0)
private Long id;
#JoinColumn(name = "FATHERID", referencedColumnName = "ID")
#ManyToOne(optional = false,fetch= FetchType.LAZY)
private Father father;
}
EJB Method
public Father findFather(long id) {
Father fath = em.find(Father.class, id);
PersistenceUnitUtil util = em.getEntityManagerFactory().getPersistenceUnitUtil();
System.out.println("mother isloaded="+util.isLoaded(fath,"mother"));
System.out.println("friendList isloaded="+util.isLoaded(fath,"friendList"));
return fath;
}
Client Side Call over Hessian
public void findFather() {
try {
IManager manager = ProxyHelper.getStub();
//find by father id
Father father = manager.findFather(3500L);
System.out.println("Father=" + father);
System.out.println("father's friends=" + father.getFriendList());
System.out.println("mother=" + father.getMother());
} catch (MalformedURLException ex) {
}
}
everything works fine, but when view server log and Father entity related parties I discovered
that LazyLoaded anotated fields is filled from database.
Server Log
FINEST: Begin deploying Persistence Unit test; session file:/C:/netbeans/projects/JPATestServer/build/web/WEB-INF/classes/_test; state Predeployed; factoryCount 1
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
FINEST: property=eclipselink.target-server; value=SunAS9; translated value=org.eclipse.persistence.platform.server.sunas.SunAS9ServerPlatform
FINEST: property=eclipselink.logging.level; value=FINEST; translated value=FINEST
FINEST: property=eclipselink.logging.parameters; value=true
FINEST: property=eclipselink.logging.level; value=FINEST; translated value=FINEST
FINEST: property=eclipselink.logging.parameters; value=true
FINEST: property=eclipselink.cache.shared.default; value=false; translated value=false
INFO: EclipseLink, version: Eclipse Persistence Services - 2.3.2.v20111125-r10461
FINEST: Database platform: org.eclipse.persistence.platform.database.oracle.Oracle11Platform, regular expression: (?i)oracle.*11
FINEST: Database platform: org.eclipse.persistence.platform.database.oracle.Oracle10Platform, regular expression: (?i)oracle.*10
FINEST: Database platform: org.eclipse.persistence.platform.database.oracle.Oracle9Platform, regular expression: (?i)oracle.*9
FINEST: Database platform: org.eclipse.persistence.platform.database.oracle.OraclePlatform, regular expression: (?i)oracle.*
FINEST: Database platform: org.eclipse.persistence.platform.database.SQLAnywherePlatform, regular expression: SQL\ Anywhere.*
FINEST: Database platform: org.eclipse.persistence.platform.database.SybasePlatform, regular expression: (?i)(sybase.*)|(adaptive\ server\ enterprise.*)|(SQL\ Server.*)
FINEST: Database platform: org.eclipse.persistence.platform.database.SQLServerPlatform, regular expression: (?i)microsoft.*
FINE: Detected database platform: org.eclipse.persistence.platform.database.SQLServerPlatform
CONFIG: connecting(DatabaseLogin(
platform=>DatabasePlatform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
CONFIG: Connected: jdbc:jtds:sqlserver:
User: user
Database: Microsoft SQL Server Version: 10.50.1600
Driver: jTDS Type 4 JDBC Driver for MS SQL Server and Sybase Version: 1.2.5
FINEST: Connection acquired from connection pool [read].
FINEST: Connection released to connection pool [read].
CONFIG: connecting(DatabaseLogin(
platform=>SQLServerPlatform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
CONFIG: Connected: jdbc:jtds:sqlserver:
User: user
Database: Microsoft SQL Server Version: 10.50.1600
Driver: jTDS Type 4 JDBC Driver for MS SQL Server and Sybase Version: 1.2.5
FINEST: sequencing connected, state is Preallocation_Transaction_NoAccessor_State
FINEST: sequence child_uid: preallocation size 1
FINEST: sequence friend_uid: preallocation size 1
FINEST: sequence father_uid: preallocation size 1
FINEST: sequence mother_uid: preallocation size 1
INFO: file:/C:/netbeans/projects/JPATestServer/build/web/WEB-INF/classes/_test login successful
WARNING: Multiple [2] JMX MBeanServer instances exist, we will use the server at index [0] : [com.sun.enterprise.v3.admin.DynamicInterceptor#266bad10].
FINER: JMX MBeanServer instance found: [com.sun.enterprise.v3.admin.DynamicInterceptor#266bad10], # of beans: [21], domain: [DefaultDomain] at index: [0].
WARNING: JMX MBeanServer in use: [com.sun.enterprise.v3.admin.DynamicInterceptor#266bad10] from index [0]
FINER: JMX MBeanServer instance found: [com.sun.jmx.mbeanserver.JmxMBeanServer#6f7adf19], # of beans: [24], domain: [DefaultDomain] at index: [1].
WARNING: JMX MBeanServer in use: [com.sun.jmx.mbeanserver.JmxMBeanServer#6f7adf19] from index [1]
FINEST: Registered MBean: org.eclipse.persistence.services.mbean.MBeanDevelopmentServices[TopLink:Name=Development-file_/C_/netbeans/projects/JPATestServer/build/web/WEB-INF/classes/_test,Type=Configuration] on server com.sun.jmx.mbeanserver.JmxMBeanServer#6f7adf19
FINEST: Registered MBean: org.eclipse.persistence.services.glassfish.MBeanGlassfishRuntimeServices[TopLink:Name=Session(file_/C_/netbeans/projects/JPATestServer/build/web/WEB-INF/classes/_test)] on server com.sun.jmx.mbeanserver.JmxMBeanServer#6f7adf19
FINEST: EclipseLink JMX Runtime Services is referencing the [Platform ConversionManager] ClassLoader at: [WebappClassLoader (delegate=true; repositories=WEB-INF/classes/)]
FINEST: The applicationName for the MBean attached to session [file:/C:/netbeans/projects/JPATestServer/build/web/WEB-INF/classes/_test] is [unknown]
FINEST: The moduleName for the MBean attached to session [file:/C:/netbeans/projects/JPATestServer/build/web/WEB-INF/classes/_test] is [unknown]
FINER: Canonical Metamodel class [org.dima.model.Child_] not found during initialization.
FINER: Canonical Metamodel class [org.dima.model.Friend_] not found during initialization.
FINER: Canonical Metamodel class [org.dima.model.Father_] not found during initialization.
FINER: Canonical Metamodel class [org.dima.model.Mother_] not found during initialization.
FINEST: End deploying Persistence Unit test; session file:/C:/netbeans/projects/JPATestServer/build/web/WEB-INF/classes/_test; state Deployed; factoryCount 1
FINER: client acquired: 50658177
FINER: TX binding to tx mgr, status=STATUS_ACTIVE
FINER: acquire unit of work: 1008456627
FINEST: Execute query ReadObjectQuery(name="readObject" referenceClass=Father sql="SELECT ID, NAME, SURNAME FROM LSDB.dbo.FATHER WHERE (ID = ?)")
FINEST: Connection acquired from connection pool [read].
FINEST: reconnecting to external connection pool
FINE: SELECT ID, NAME, SURNAME FROM LSDB.dbo.FATHER WHERE (ID = ?)
bind => [3500]
FINEST: Connection released to connection pool [read].
INFO: mother isloaded=false
INFO: friendList isloaded=false
FINER: TX beforeCompletion callback, status=STATUS_ACTIVE
FINER: begin unit of work commit
FINER: TX afterCompletion callback, status=COMMITTED
FINER: end unit of work commit
FINER: release unit of work
FINER: client released
FINEST: Execute query ReadAllQuery(name="file:/C:/netbeans/projects/JPATestServer/build/web/WEB-INF/classes/_test" referenceClass=Friend )
FINEST: Connection acquired from connection pool [read].
FINEST: reconnecting to external connection pool
**FINE: SELECT ID, NAME, SURNAME, FATHERID FROM LSDB.dbo.FRIEND WHERE (FATHERID = ?)
bind => [3500]**
FINEST: Connection released to connection pool [read].
FINEST: Register the existing object org.dima.model.Friend[ id=17496 ]
FINEST: Register the existing object org.dima.model.Friend[ id=17497 ]
FINEST: Register the existing object org.dima.model.Friend[ id=17498 ]
FINEST: Register the existing object org.dima.model.Friend[ id=17499 ]
FINEST: Register the existing object org.dima.model.Friend[ id=17500 ]
Why JPA provider executes this
SELECT ID, NAME, SURNAME, FATHERID FROM LSDB.dbo.FRIEND WHERE (FATHERID = ?)
bind => [3500]
Any idea?
Lazy loading is only done for xToMany relation in a Java SE environment by default (since EclipseLink can use IndirectList where collections are used). If you want to lazy load xToOne relations you have to use class weaving.
Lazy fetch type is working. Lazy relationships allow delaying the fetching of the referenced entities until they are first accessed, which seems to be happenging when you call father.getFriendList(). If it were not working, this call would do nothing and the relationship fetched immediately when the father was read in.
EclipseLink allows accessing a lazy relationship as long as the connection is still available as described here: http://dev.eclipse.org/mhonarc/lists/eclipselink-users/msg05258.html If you serialize the entity you will get the exception as the context to read in the relationship will not be available.
If you wish an exception be thrown instead when you access a lazy relationship on a detached but not serialized entity, please file an enhancement request in EclipseLink.
The EAGER strategy is a requirement on the persistence provider
runtime that the value must be eagerly fetched. The LAZY strategy is a
hint to the persistence provider runtime.
Found this answer here. JPA fetchType.Lazy is not working
One more thing: JPA uses weaving to accomplish this. wiki-eclipse