Iam using criteria queries with EclipseLink as JPA . I need to cache the query results based on their parameters . When I used query.setHint("eclipselink.QUERY_RESULTS_CACHE", "TRUE") it still fires query to the database. How can I use it in context of criteria queries ?
Here I set my query and their hints and addNamedQuery
Query query = psEntityManager.getEntityManager().createQuery(criteriaQuery);// Creating Query to supply Values
query.setHint("eclipselink.QUERY_RESULTS_CACHE", "TRUE");
query.setHint(QueryHints.QUERY_TYPE,QueryType.ReadObject);
psEntityManager.getEntityManager().getEntityManagerFactory().addNamedQuery("query1", query);
Here is my output :
Query1-----------
[EL Fine]: sql: 2013-10-10 21:33:35.495--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, ADDRESSLINE1, ADDRESSLINE2, PHONENUMBER, fkCityId, fkPersonId FROM ADDRESS WHERE (fkPersonId = ?)
bind => [2]
[EL Fine]: sql: 2013-10-10 21:33:35.527--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, CITYNAME, PINCODE, fkStateId FROM CITY WHERE (PRIMARYKEY = ?)
bind => [2]
[EL Fine]: sql: 2013-10-10 21:33:35.528--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, STATENAME FROM STATE WHERE (PRIMARYKEY = ?)
bind => [1]
[EL Fine]: sql: 2013-10-10 21:33:35.531--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, AGE, DOB, FIRSTNAME, LASTNAME, SEX, TIMESTAMP, fkDepartmentId FROM PERSON WHERE (PRIMARYKEY = ?)
bind => [2]
[EL Fine]: sql: 2013-10-10 21:33:35.541--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, DEPTNAME FROM DEPARTMENT WHERE (PRIMARYKEY = ?)
bind => [2]
[EL Fine]: sql: 2013-10-10 21:33:35.547--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, CITYNAME, PINCODE, fkStateId FROM CITY WHERE (PRIMARYKEY = ?)
bind => [5]
[EL Fine]: sql: 2013-10-10 21:33:35.548--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, STATENAME FROM STATE WHERE (PRIMARYKEY = ?)
bind => [3]
[EL Fine]: sql: 2013-10-10 21:33:35.551--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, CITYNAME, PINCODE, fkStateId FROM CITY WHERE (PRIMARYKEY = ?)
bind => [8]
[EL Fine]: sql: 2013-10-10 21:33:35.553--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, STATENAME FROM STATE WHERE (PRIMARYKEY = ?)
bind => [4]
Query2-----------
[EL Fine]: sql: 2013-10-10 21:33:35.557--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, ADDRESSLINE1, ADDRESSLINE2, PHONENUMBER, fkCityId, fkPersonId FROM ADDRESS WHERE (fkPersonId = ?)
bind => [2]
Query3-----------
[EL Fine]: sql: 2013-10-10 21:33:35.56--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, ADDRESSLINE1, ADDRESSLINE2, PHONENUMBER, fkCityId, fkPersonId FROM ADDRESS WHERE (fkPersonId = ?)
bind => [2]
Query4-----------
[EL Fine]: sql: 2013-10-10 21:33:35.563--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, ADDRESSLINE1, ADDRESSLINE2, PHONENUMBER, fkCityId, fkPersonId FROM ADDRESS WHERE (fkPersonId = ?)
bind => [2]
Remove the query.setHint(QueryHints.QUERY_TYPE,QueryType.ReadObject), or call it first. The query_type changes the underlying query object, and not all the hints might be copied into the new object. It seems unnecessary anyway.
Related
I get this error when trying to insert a value into my join table in my database:
Detail: Key (Id)=(0) is not present in table "GroceryItems".
Full error:
Executing DbCommand [Parameters=[#p0='1', #p1='fsfsasf' (Nullable = false), #p2='0', #p3='df2sssfad' (Nullable = false), #p4=NULL, #p5='0', #p6='0', #p7='yosadsfdfsaff' (Nullable = false), #p8='0', #p9='0', #p10='[{"Id":11,"IconCodePoint":23145,"Name":"sdaf"}]' (Nullable = false), #p11=NULL, #p12='fMs' (Nullable = false), #p13='ffsfffs' (Nullable = false), #p14='Beacdsfff2dfh Rd' (Nullable = false), #p15=NULL, #p16=NULL], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItems" ("Id", "Brand", "CurrentRevisionId", "Description", "Image", "IsNotVeganCount", "IsVeganCount", "Name", "Rating", "RatingsCount", "Tags")
VALUES (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9, #p10);
INSERT INTO "GroceryStores" ("City", "Name", "PlaceId", "Street", "StreetNumber", "Suburb")
VALUES (#p11, #p12, #p13, #p14, #p15, #p16)
RETURNING "Id";
info: 03/26/2021 18:07:09.846 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (6ms) [Parameters=[#p0='1', #p1='fsfsasf' (Nullable = false), #p2='0', #p3='df2sssfad' (Nullable = false), #p4=NULL, #p5='0', #p6='0', #p7='yosadsfdfsaff' (Nullable = false), #p8='0', #p9='0', #p10='[{"Id":11,"IconCodePoint":23145,"Name":"sdaf"}]' (Nullable = false), #p11=NULL, #p12='fMs' (Nullable = false), #p13='ffsfffs' (Nullable = false), #p14='Beacdsfff2dfh Rd' (Nullable = false), #p15=NULL, #p16=NULL], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItems" ("Id", "Brand", "CurrentRevisionId", "Description", "Image", "IsNotVeganCount", "IsVeganCount", "Name", "Rating", "RatingsCount", "Tags")
VALUES (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9, #p10);
INSERT INTO "GroceryStores" ("City", "Name", "PlaceId", "Street", "StreetNumber", "Suburb")
VALUES (#p11, #p12, #p13, #p14, #p15, #p16)
RETURNING "Id";
dbug: 03/26/2021 18:07:09.847 CoreEventId.ForeignKeyChangeDetected[10803] (Microsoft.EntityFrameworkCore.ChangeTracking)
The foreign key property 'GroceryStore.Id' was detected as changed from '-2147482642' to '8' for entity with key '{Id: 8}'.
dbug: 03/26/2021 18:07:09.847 CoreEventId.ForeignKeyChangeDetected[10803] (Microsoft.EntityFrameworkCore.ChangeTracking)
The foreign key property 'GroceryItemGroceryStore.EstablishmentId' was detected as changed from '-2147482642' to '8' for entity with key '{VeganItemId: 1, EstablishmentId: 8}'.
dbug: 03/26/2021 18:07:09.847 RelationalEventId.DataReaderDisposing[20300] (Microsoft.EntityFrameworkCore.Database.Command)
The foreign key property 'GroceryItemGroceryStore.EstablishmentId' was detected as changed from '-2147482642' to '8' for entity with key '{VeganItemId: 1, EstablishmentId: 8}'.
dbug: 03/26/2021 18:07:09.847 RelationalEventId.DataReaderDisposing[20300] (Microsoft.EntityFrameworkCore.Database.Command)
A data reader was disposed.
dbug: 03/26/2021 18:07:09.847 RelationalEventId.CommandCreating[20103] (Microsoft.EntityFrameworkCore.Database.Command)
Creating DbCommand for 'ExecuteReader'.
dbug: 03/26/2021 18:07:09.847 RelationalEventId.CommandCreated[20104] (Microsoft.EntityFrameworkCore.Database.Command)
Created DbCommand for 'ExecuteReader' (0ms).
dbug: 03/26/2021 18:07:09.847 RelationalEventId.CommandExecuting[20100] (Microsoft.EntityFrameworkCore.Database.Command)
Executing DbCommand [Parameters=[#p17='8', #p18='1', #p19='0', #p20='0', #p21='0', #p22='2'], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItemGroceryStores" ("EstablishmentId", "VeganItemId", "Id", "InEstablishmentCount", "NotInEstablishmentCount", "Price")
VALUES (#p17, #p18, #p19, #p20, #p21, #p22);
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (7ms) [Parameters=[#p17='8', #p18='1', #p19='0', #p20='0', #p21='0', #p22='2'], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItemGroceryStores" ("EstablishmentId", "VeganItemId", "Id", "InEstablishmentCount", "NotInEstablishmentCount", "Price")
VALUES (#p17, #p18, #p19, #p20, #p21, #p22);
Microsoft.EntityFrameworkCore.Database.Command: Error: Failed executing DbCommand (7ms) [Parameters=[#p17='8', #p18='1', #p19='0', #p20='0', #p21='0', #p22='2'], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItemGroceryStores" ("EstablishmentId", "VeganItemId", "Id", "InEstablishmentCount", "NotInEstablishmentCount", "Price")
VALUES (#p17, #p18, #p19, #p20, #p21, #p22);
fail: 03/26/2021 18:07:09.858 RelationalEventId.CommandError[20102] (Microsoft.EntityFrameworkCore.Database.Command)
Failed executing DbCommand (7ms) [Parameters=[#p17='8', #p18='1', #p19='0', #p20='0', #p21='0', #p22='2'], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItemGroceryStores" ("EstablishmentId", "VeganItemId", "Id", "InEstablishmentCount", "NotInEstablishmentCount", "Price")
VALUES (#p17, #p18, #p19, #p20, #p21, #p22);
dbug: 03/26/2021 18:07:09.883 RelationalEventId.TransactionDisposed[20204] (Microsoft.EntityFrameworkCore.Database.Transaction)
Disposing transaction.
dbug: 03/26/2021 18:07:09.883 RelationalEventId.ConnectionClosing[20002] (Microsoft.EntityFrameworkCore.Database.Connection)
Closing connection to database 'vepo_dev_db' on server 'tcp://localhost:5432'.
dbug: 03/26/2021 18:07:09.883 RelationalEventId.ConnectionClosed[20003] (Microsoft.EntityFrameworkCore.Database.Connection)
Microsoft.EntityFrameworkCore.Database.Command: Error: Failed executing DbCommand (7ms) [Parameters=[#p17='8', #p18='1', #p19='0', #p20='0', #p21='0', #p22='2'], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItemGroceryStores" ("EstablishmentId", "VeganItemId", "Id", "InEstablishmentCount", "NotInEstablishmentCount", "Price")
VALUES (#p17, #p18, #p19, #p20, #p21, #p22);
fail: 03/26/2021 18:07:09.858 RelationalEventId.CommandError[20102] (Microsoft.EntityFrameworkCore.Database.Command)
Failed executing DbCommand (7ms) [Parameters=[#p17='8', #p18='1', #p19='0', #p20='0', #p21='0', #p22='2'], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItemGroceryStores" ("EstablishmentId", "VeganItemId", "Id", "InEstablishmentCount", "NotInEstablishmentCount", "Price")
VALUES (#p17, #p18, #p19, #p20, #p21, #p22);
dbug: 03/26/2021 18:07:09.883 RelationalEventId.TransactionDisposed[20204] (Microsoft.EntityFrameworkCore.Database.Transaction)
Disposing transaction.
dbug: 03/26/2021 18:07:09.883 RelationalEventId.ConnectionClosing[20002] (Microsoft.EntityFrameworkCore.Database.Connection)
Closing connection to database 'vepo_dev_db' on server 'tcp://localhost:5432'.
dbug: 03/26/2021 18:07:09.883 RelationalEventId.ConnectionClosed[20003] (Microsoft.EntityFrameworkCore.Database.Connection)
Closed connection to database 'vepo_dev_db' on server 'tcp://localhost:5432'.
fail: Microsoft.EntityFrameworkCore.Update[10000]
An exception occurred in the database while saving changes for context type 'Vepo.Data.VepoContext'.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
---> Npgsql.PostgresException (0x80004005): 23503: insert or update on table "GroceryItemGroceryStores" violates foreign key constraint "FK_GroceryItemGroceryStores_GroceryItems_Id"
at Npgsql.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|194_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
2
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
2
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
Exception data:
Severity: ERROR
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
Exception data:
Severity: ERROR
SqlState: 23503
MessageText: insert or update on table "GroceryItemGroceryStores" violates foreign key constraint "FK_GroceryItemGroceryStores_GroceryItems_Id"
Detail: Key (Id)=(0) is not present in table "GroceryItems".
SchemaName: public
TableName: GroceryItemGroceryStores
ConstraintName: FK_GroceryItemGroceryStores_GroceryItems_Id
File: ri_triggers.c
Line: 3266
Routine: ri_ReportViolation
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
The 3 tables are GroceryItems, GroceryStores, and the join table GroceryItemGroceryStores.
Here is my code using the fluent API to set up a many to many relationship.
modelBuilder.Entity<GroceryStore>(gs =>
{
gs.HasIndex(gs => gs.PlaceId).IsUnique();
gs
.HasMany(s => s.VeganItems)
.WithMany(vi => vi.Establishments)
.UsingEntity<GroceryItemGroceryStore>
(gigs => gigs.HasOne<GroceryItem>().WithMany().HasForeignKey("Id"),
gigs => gigs.HasOne<GroceryStore>().WithMany().HasForeignKey("Id"));
});
Here are my actual database tables:
It doesn't look like this error should exist, GroceryItems has a column Id which is the primary key. Why does the error occur?
Here is the controller endpoint that runs:
// POST: api/GroceryItemGroceryStores
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<GroceryItemGroceryStore>> PostGroceryItemGroceryStore(GroceryItemGroceryStore groceryItemGroceryStore)
{
_context.GroceryItemGroceryStores.Add(groceryItemGroceryStore);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (GroceryItemGroceryStoreExists(groceryItemGroceryStore.VeganItemId))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtAction("GetGroceryItemGroceryStore", new { id = groceryItemGroceryStore.VeganItemId }, groceryItemGroceryStore);
}
JSON payload sent:
{
"veganItem": {
"name": "yosadsfdfsaff",
"brand": "fsfsasf",
"description": "df2sssfad",
"tags": [
{
"name": "sdaf",
"id": "11",
"iconCodePoint": 23145
}
]
},
"establishment": {
"name": "fMs",
"street": "Beacdsfff2dfh Rd",
"placeId": "ffsfffs"
},
"price": 2.00
}
debugger of class instance being inserted:
I have found some more details to the error - It seems to be performing an update if you see the error (even though I am just doing .Add() to add to the database:
When I try to insert a GroceryItem to the GroceryItem table nothing goes in and it returns an empty array with no errors.
It kinda seems to me like the .Add() is performing the wrong thing (update instead of insert). I have added the raw SQL into the error near the top of the question.
Removing .HasForeignKey("Id") made it work.
modelBuilder.Entity<GroceryStore>(gs =>
{
gs.HasIndex(gs => gs.PlaceId).IsUnique();
gs.HasMany(gs => gs.VeganItems)
.WithMany(vi => vi.Establishments)
.UsingEntity<GroceryItemGroceryStore>
(gigs => gigs.HasOne<GroceryItem>().WithMany(),
gigs => gigs.HasOne<GroceryStore>().WithMany());
});
I thought I needed the HasForeignKey because my database had all these foreign key constraints with VeganItemId and EstablishmentId. I thought that it was expecting my primary keys to be VeganItemId and EstablishmentId:
But I suppose the (Id) at the end of all of those means it is just Id after all.
Why jpa binding enum parameter as varbinary?
#Query(value = "select * from person where skin in :skin",nativeQuery=true)
List<People> findInSkins(Skin[] skin);
Here is the log
Hibernate: select * from person where skin in (?, ?)
2019-11-12 18:59:57.282 TRACE 141600 --- [nio-8081-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARBINARY] - [Yellow]
2019-11-12 18:59:57.283 TRACE 141600 --- [nio-8081-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARBINARY] - [Black]
If you want jpa to bind it as a String you should use this decorator:
**#Enumerated(EnumType.STRING)**
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.
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
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