How to properly create Nested Join using Criteria Builder - jpa

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

Related

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.

JPA Connection for eclipselink as a provider and oracle as a database

I am trying to execute simple JPA mapping using EclipseLink as jpa provider.
[![Persistence and Project Structure][1]][1]
above image explains the project structure and persistence.xml.
above mentioned database details, i have checked in oracle toad. I am able to access specified schema as shown below.
[![opening database connection ][2]][2]
in above image, you could see the connection.
following is the POJO
it is a simple pojo class which has one field which i defined as a primary key and other fields.
package com.sun.arise;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Sun")
public class Sun {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int sunid;
#Column(name="DAY")
private String day;
#Column(name="MONTH")
private String month;
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public int getSunId()
{
return sunid;
}
#Override
public String toString()
{
return getSunId()+"\n"+getDay()+"\n"+getMonth();
}
}
to persist above pojo i wrote following class
package com.sun.sunset;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.sun.arise.Sun;
public class TestSun {
public static void main(String args[])
{
String persistenceUnitName="myAttemptAtJPA";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
EntityManager em = emf.createEntityManager();
Sun z = new Sun();
z.setDay("Saturday");
z.setMonth("January");
em.getTransaction().begin();
em.persist(z);
em.getTransaction().commit();
}
}
after executing i am getting following errors
i am not sure error is because it is not able to find persistence.xml in META-INF folder. it is not able to find url and driver.
[EL Fine]: server: 2016-06-14 17:02:31.478--Thread(Thread[main,5,main])--Configured server platform: org.eclipse.persistence.platform.server.NoServerPlatform
[EL Config]: metadata: 2016-06-14 17:02:31.592--ServerSession(19166103)--Thread(Thread[main,5,main])--The access type for the persistent class [class com.sun.arise.Sun] is set to [FIELD].
[EL Config]: metadata: 2016-06-14 17:02:31.612--ServerSession(19166103)--Thread(Thread[main,5,main])--The alias name for the entity class [class com.sun.arise.Sun] is being defaulted to: Sun.
[EL Config]: metadata: 2016-06-14 17:02:31.627--ServerSession(19166103)--Thread(Thread[main,5,main])--The column name for element [sunid] is being defaulted to: SUNID.
[EL Info]: 2016-06-14 17:02:31.65--ServerSession(19166103)--Thread(Thread[main,5,main])--EclipseLink, version: Eclipse Persistence Services - 2.6.3.v20160428-59c81c5
[EL Severe]: ejb: 2016-06-14 17:02:31.652--ServerSession(19166103)--Thread(Thread[main,5,main])--Exception [EclipseLink-4021] (Eclipse Persistence Services - 2.6.3.v20160428-59c81c5): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: Unable to acquire a connection from driver [null], user [null] and URL [null]. Verify that you have set the expected driver class and URL. Check your login, persistence.xml or sessions.xml resource. The jdbc.driver property should be set to a class that is compatible with your database platform
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4021] (Eclipse Persistence Services - 2.6.3.v20160428-59c81c5): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: Unable to acquire a connection from driver [null], user [null] and URL [null]. Verify that you have set the expected driver class and URL. Check your login, persistence.xml or sessions.xml resource. The jdbc.driver property should be set to a class that is compatible with your database platform
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:815)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:205)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:305)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:337)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:303)
at com.sun.sunset.TestSun.main(TestSun.java:15)
Caused by: Exception [EclipseLink-4021] (Eclipse Persistence Services - 2.6.3.v20160428-59c81c5): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: Unable to acquire a connection from driver [null], user [null] and URL [null]. Verify that you have set the expected driver class and URL. Check your login, persistence.xml or sessions.xml resource. The jdbc.driver property should be set to a class that is compatible with your database platform
at org.eclipse.persistence.exceptions.DatabaseException.unableToAcquireConnectionFromDriverException(DatabaseException.java:383)
at org.eclipse.persistence.sessions.DefaultConnector.connect(DefaultConnector.java:91)
at org.eclipse.persistence.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:162)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.setOrDetectDatasource(DatabaseSessionImpl.java:207)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:760)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:265)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:731)
... 5 more
please let me know if any more information is required.
thanks
[1]: http://i.stack.imgur.com/PD0Ru.png
[2]: http://i.stack.imgur.com/iXEN0.png
There are no such persistence properties javax.persistence.driver, etc.
They are
javax.persistence.jdbc.driver
javax.persistence.jdbc.user
etc

Eclipse Link JPA native update query thowring deadlock exception

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

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'"

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