transaction isolation level (READ UNCOMMITTED) of Spring Batch - sql-server

I want to set transaction isolation level to READ UNCOMMITTED, but is doesn't work.
Here is my job source.
TestJobConfiguration.java
#Slf4j
#Configuration
public class TestJobConfiguration {
#Autowired
private JobBuilderFactory jobBuilders;
#Autowired
private CustomJobExecutionListener customJobExecutionListener;
#Autowired
private JdbcTemplate jdbcTemplate;
#Autowired
private StepBuilderFactory stepBuilders;
#Bean(name = "testJob")
public Job job() {
JobBuilder jobBuilder = jobBuilders.get("testJob").listener(customJobExecutionListener);
Step step = stepBuilders.get("testStep").tasklet(count()).transactionAttribute(transactionAttr())
.build();
return jobBuilder.start(step).build();
}
public TransactionAttribute transactionAttr() {
RuleBasedTransactionAttribute tr = new RuleBasedTransactionAttribute();
tr.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
return tr;
}
public Tasklet count() {
return new Tasklet() {
#Override
public RepeatStatus execute(StepContribution contribution, ChunkContext context) {
StringBuilder countSql = new StringBuilder();
countSql.append(" SELECT COUNT(id)");
countSql.append(" FROM user");
log.debug("test start");
int count = jdbcTemplate.queryForObject(countSql.toString(), Integer.class);
contribution.incrementWriteCount(count);
log.debug("test end");
log.debug("count : {}", count);
return RepeatStatus.FINISHED;
}
};
}
}
I executed below sql statement in Microsoft SQL Server Management Studio, and executed TestJob.
begin tran
delete from user
I expected to complete job, but it stopped at sql execution point.
My log is below.
...
2017-08-29T12:21:23.555+09:00 DEBUG --- [ main] c.p.l.b.rank.job.TestJobConfiguration : test start
When I change my sql statement, countSql.append(" SELECT COUNT(id)"); to countSql.append(" SELECT COUNT(id) WITH (READUNCOMMITTED)"); it works.
...
2017-08-29T13:44:43.692+09:00 DEBUG --- [ main] c.p.l.b.rank.job.TestJobConfiguration : test start
2017-08-29T13:44:43.726+09:00 DEBUG --- [ main] c.p.l.b.rank.job.TestJobConfiguration : test end
2017-08-29T13:44:43.726+09:00 DEBUG --- [ main] c.p.l.b.rank.job.TestJobConfiguration : count : 15178
2017-08-29T13:44:43.747+09:00 INFO --- [ main] c.p.l.b.l.CustomJobExecutionListener :
<!-----------------------------------------------------------------
Protocol for testJob
Started : Tue Aug 29 13:44:43 KST 2017
Finished : Tue Aug 29 13:44:43 KST 2017
Exit-Code : COMPLETED
Exit-Descr. :
Status : COMPLETED
Job-Parameter:
date=2017-08-29 13:44:43 +0900
JOB process time : 0sec
----------------------------------------------------------------->
Why doesn't work isolation level of transaction attribute??

Related

Springboot #DataJpaTest Integration test with external sql server db

I have below repository class in my spring boot project. This repository has a method that returns Inventory data from the SQL server. This is working on my project.
#Repository
public interface InventoryRepository extends JpaRepository<Inventory, Integer> {
Inventory findByInventoryIdAndCompanyId(Integer inventoryId, Integer companyId);
}
I want to write a integration for the repository which should get data from dev and test environment SQL server DB.
This dev and test environment db has data already.
Below are the application.yml files in my resources folder (I have changed url and credential intentionally to show here).
application.yml :
spring:
profiles.active: development
application-developement.yml :
spring:
profiles: development
spring.datasource.type: com.zaxxer.hikari.HikariDataSource
spring.datasource.jdbc-url: jdbc:sqlserver://22.22.22.22:1533;instanceName=SQLSVR;databaseName=dev
spring.datasource.username: admin
spring.datasource.password: admin
spring.datasource.driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
application-test.yml :
spring:
profiles: test
spring.datasource.type: com.zaxxer.hikari.HikariDataSource
spring.datasource.jdbc-url: jdbc:sqlserver://11.11.11.11:1533;instanceName=SQLSVR;databaseName=qa
spring.datasource.url: jdbc:sqlserver://11.11.11.11:1533;instanceName=SQLSVR;databaseName=qa
spring.datasource.username: admin
spring.datasource.password: admin
spring.datasource.driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
Below is the test class for my repository.
#ExtendWith(SpringExtension.class)
#DataJpaTest
#ContextConfiguration
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class InventoryRepositoryTest {
#Autowired
InventoryRepository inventoryRepository;
#Test
public void getRepositoryByIdTest () {
Assertions.assertEquals(1,inventoryRepository.findByInventoryIdAndCompanyId(1,1));
}
}
Below is the error I am getting while performing this test
2021-10-18 03:35:38.917 INFO 11968 --- [ main] o.s.t.c.transaction.TransactionContext : Began transaction (1) for test context [DefaultTestContext#18d87d80 testClass = InventoryRepositoryTest, testInstance = com.cropin.mwarehouse.common.repository.InventoryRepositoryTest#437da279, testMethod = getRepositoryByIdTest#InventoryRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#618425b5 testClass = InventoryRepositoryTest, locations = '{}', classes = '{class com.cropin.mwarehouse.CropinMWarehouseServiceApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer#58695725 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#4b2bac3f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#26794848, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer#6ad82709, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer#351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#fb6c1252, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#158a8276], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager#f310675]; rollback [true]
2021-10-18 03:35:38.963 DEBUG 11968 --- [ main] org.hibernate.SQL :
select
inventory0_.inventoryId as inventor1_10_,
inventory0_.createdBy as createdB2_10_,
inventory0_.createdDate as createdD3_10_,
inventory0_.lastModifiedBy as lastModi4_10_,
inventory0_.lastModifiedDate as lastModi5_10_,
inventory0_.balanceWeight as balanceW6_10_,
inventory0_.batchCreationDate as batchCre7_10_,
inventory0_.batchNumber as batchNum8_10_,
inventory0_.clientId as clientId9_10_,
inventory0_.companyId as company10_10_,
inventory0_.currencyUnitId as currenc11_10_,
inventory0_.dateOfEntry as dateOfE12_10_,
inventory0_.harvestReferenceId as harvest13_10_,
inventory0_.inventoryStatus as invento14_10_,
inventory0_.isActive as isActiv15_10_,
inventory0_.itemId as itemId16_10_,
inventory0_.locationId as locatio17_10_,
inventory0_.parentInventoryId as parentI18_10_,
inventory0_.processId as process19_10_,
inventory0_.quantity as quantit20_10_,
inventory0_.quantityBalance as quantit21_10_,
inventory0_.supplierId as supplie22_10_,
inventory0_.unitPrice as unitPri23_10_,
inventory0_.weight as weight24_10_
from
inv.Inventory inventory0_
where
inventory0_.inventoryId=?
and inventory0_.companyId=?
Hibernate:
select
inventory0_.inventoryId as inventor1_10_,
inventory0_.createdBy as createdB2_10_,
inventory0_.createdDate as createdD3_10_,
inventory0_.lastModifiedBy as lastModi4_10_,
inventory0_.lastModifiedDate as lastModi5_10_,
inventory0_.balanceWeight as balanceW6_10_,
inventory0_.batchCreationDate as batchCre7_10_,
inventory0_.batchNumber as batchNum8_10_,
inventory0_.clientId as clientId9_10_,
inventory0_.companyId as company10_10_,
inventory0_.currencyUnitId as currenc11_10_,
inventory0_.dateOfEntry as dateOfE12_10_,
inventory0_.harvestReferenceId as harvest13_10_,
inventory0_.inventoryStatus as invento14_10_,
inventory0_.isActive as isActiv15_10_,
inventory0_.itemId as itemId16_10_,
inventory0_.locationId as locatio17_10_,
inventory0_.parentInventoryId as parentI18_10_,
inventory0_.processId as process19_10_,
inventory0_.quantity as quantit20_10_,
inventory0_.quantityBalance as quantit21_10_,
inventory0_.supplierId as supplie22_10_,
inventory0_.unitPrice as unitPri23_10_,
inventory0_.weight as weight24_10_
from
inv.Inventory inventory0_
where
inventory0_.inventoryId=?
and inventory0_.companyId=?
2021-10-18 03:35:39.142 DEBUG 11968 --- [ main] org.hibernate.SQL :
select
companymas0_.companyId as companyI1_1_0_,
companymas0_.createdBy as createdB2_1_0_,
companymas0_.createdDate as createdD3_1_0_,
companymas0_.lastModifiedBy as lastModi4_1_0_,
companymas0_.lastModifiedDate as lastModi5_1_0_,
companymas0_.companyAddress as companyA6_1_0_,
companymas0_.companyCode as companyC7_1_0_,
companymas0_.companyDesc as companyD8_1_0_,
companymas0_.companyLogo as companyL9_1_0_,
companymas0_.companyName as company10_1_0_,
companymas0_.companyPreferredSubDomain as company11_1_0_,
companymas0_.contactEmail as contact12_1_0_,
companymas0_.contactNumber as contact13_1_0_,
companymas0_.defaultRadiusForGeoFencing as default14_1_0_,
companymas0_.fiscalMonth as fiscalM15_1_0_,
companymas0_.isGDPRRequired as isGDPRR16_1_0_,
companymas0_.isActive as isActiv17_1_0_,
companymas0_.isBlueToothRequired as isBlueT18_1_0_,
companymas0_.isGeoFencingRequired as isGeoFe19_1_0_,
companymas0_.isHarvestPaid as isHarve20_1_0_,
companymas0_.isShareImage as isShare21_1_0_,
companymas0_.isVerified as isVerif22_1_0_,
companymas0_.isZohoEnable as isZohoE23_1_0_,
companymas0_.planTypeId as planTyp24_1_0_,
companymas0_.primaryCountry as primary25_1_0_,
companymas0_.sTA as sTA26_1_0_,
companymas0_.webSite as webSite27_1_0_
from
dbo.CompanyMaster companymas0_
where
companymas0_.companyId=?
Hibernate:
select
companymas0_.companyId as companyI1_1_0_,
companymas0_.createdBy as createdB2_1_0_,
companymas0_.createdDate as createdD3_1_0_,
companymas0_.lastModifiedBy as lastModi4_1_0_,
companymas0_.lastModifiedDate as lastModi5_1_0_,
companymas0_.companyAddress as companyA6_1_0_,
companymas0_.companyCode as companyC7_1_0_,
companymas0_.companyDesc as companyD8_1_0_,
companymas0_.companyLogo as companyL9_1_0_,
companymas0_.companyName as company10_1_0_,
companymas0_.companyPreferredSubDomain as company11_1_0_,
companymas0_.contactEmail as contact12_1_0_,
companymas0_.contactNumber as contact13_1_0_,
companymas0_.defaultRadiusForGeoFencing as default14_1_0_,
companymas0_.fiscalMonth as fiscalM15_1_0_,
companymas0_.isGDPRRequired as isGDPRR16_1_0_,
companymas0_.isActive as isActiv17_1_0_,
companymas0_.isBlueToothRequired as isBlueT18_1_0_,
companymas0_.isGeoFencingRequired as isGeoFe19_1_0_,
companymas0_.isHarvestPaid as isHarve20_1_0_,
companymas0_.isShareImage as isShare21_1_0_,
companymas0_.isVerified as isVerif22_1_0_,
companymas0_.isZohoEnable as isZohoE23_1_0_,
companymas0_.planTypeId as planTyp24_1_0_,
companymas0_.primaryCountry as primary25_1_0_,
companymas0_.sTA as sTA26_1_0_,
companymas0_.webSite as webSite27_1_0_
from
dbo.CompanyMaster companymas0_
where
companymas0_.companyId=?
2021-10-18 03:35:39.292 DEBUG 11968 --- [ main] org.hibernate.SQL :
select
locationma0_.locationId as location1_22_0_,
locationma0_.createdBy as createdB2_22_0_,
locationma0_.createdDate as createdD3_22_0_,
locationma0_.lastModifiedBy as lastModi4_22_0_,
locationma0_.lastModifiedDate as lastModi5_22_0_,
locationma0_.addressLine1 as addressL6_22_0_,
locationma0_.addressLine2 as addressL7_22_0_,
locationma0_.companyId as companyI8_22_0_,
locationma0_.coordinates as coordina9_22_0_,
locationma0_.districtId as distric10_22_0_,
locationma0_.geoId as geoId11_22_0_,
locationma0_.imageName as imageNa12_22_0_,
locationma0_.isActive as isActiv13_22_0_,
locationma0_.latitude as latitud14_22_0_,
locationma0_.locationTypeId as locatio15_22_0_,
locationma0_.longitude as longitu16_22_0_,
locationma0_.name as name17_22_0_,
locationma0_.parentLocationId as parentL18_22_0_,
locationma0_.pincode as pincode19_22_0_,
locationma0_.placeName as placeNa20_22_0_,
locationma0_.stateId as stateId21_22_0_
from
inv.LocationMaster locationma0_
where
locationma0_.locationId=?
Hibernate:
select
locationma0_.locationId as location1_22_0_,
locationma0_.createdBy as createdB2_22_0_,
locationma0_.createdDate as createdD3_22_0_,
locationma0_.lastModifiedBy as lastModi4_22_0_,
locationma0_.lastModifiedDate as lastModi5_22_0_,
locationma0_.addressLine1 as addressL6_22_0_,
locationma0_.addressLine2 as addressL7_22_0_,
locationma0_.companyId as companyI8_22_0_,
locationma0_.coordinates as coordina9_22_0_,
locationma0_.districtId as distric10_22_0_,
locationma0_.geoId as geoId11_22_0_,
locationma0_.imageName as imageNa12_22_0_,
locationma0_.isActive as isActiv13_22_0_,
locationma0_.latitude as latitud14_22_0_,
locationma0_.locationTypeId as locatio15_22_0_,
locationma0_.longitude as longitu16_22_0_,
locationma0_.name as name17_22_0_,
locationma0_.parentLocationId as parentL18_22_0_,
locationma0_.pincode as pincode19_22_0_,
locationma0_.placeName as placeNa20_22_0_,
locationma0_.stateId as stateId21_22_0_
from
inv.LocationMaster locationma0_
where
locationma0_.locationId=?
2021-10-18 03:35:39.663 INFO 11968 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext#18d87d80 testClass = InventoryRepositoryTest, testInstance = com.cropin.mwarehouse.common.repository.InventoryRepositoryTest#437da279, testMethod = getRepositoryByIdTest#InventoryRepositoryTest, testException = org.opentest4j.AssertionFailedError: expected: <1> but was: <com.cropin.mwarehouse.common.entity.Inventory#5b58f639>, mergedContextConfiguration = [MergedContextConfiguration#618425b5 testClass = InventoryRepositoryTest, locations = '{}', classes = '{class com.cropin.mwarehouse.CropinMWarehouseServiceApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer#58695725 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#4b2bac3f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#26794848, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer#6ad82709, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer#351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#fb6c1252, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#158a8276], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]
org.opentest4j.AssertionFailedError:
Expected :1
Actual :com.cropin.mwarehouse.common.entity.Inventory#5b58f639
<Click to see difference>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)
at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)
at com.cropin.mwarehouse.common.repository.InventoryRepositoryTest.getRepositoryByIdTest(InventoryRepositoryTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:74)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Below are the questions for which I am looking for an answers:
Does #DataJpaTest only works with in memory db? Here I am trying to connect with external sql server db is it really connecting to it?
If #DataJpaTest is able to connect to external sql server db then why it is failing as I already have records available for above test parameter.
3.How Can I use profiling here? There is an option as #ActiveProfile but I want to use same block of test for both the environment dev and qa, in that how this profiling will work?
4.In error log it is showing active profile as empty, what does that mean? Is it not picking up the development profile?
How can I achieve integration test connecting to my dev and qa db which already has data. I don't want to use in memory db.
Please help me out with this question.
The actual connection seems to work. #DataJpaTest works with any DataSource configuration, it just takes the opinionated approach to use an in-memory database. You already added the required code to opt-out and use your own DataSource with:
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
The actual test failure happens because you try to compare an int with an actual Java object. Either return all objects and check the size:
Assertions.assertEquals(1, inventoryRepository.findAll().size());
... or assert that the result is not null:
Assertions.assertNotNull(inventoryRepository.findByInventoryIdAndCompanyId(1,1));
Take a closer look at the assertion error:
org.opentest4j.AssertionFailedError:
Expected :1
Actual :com.cropin.mwarehouse.common.entity.Inventory#5b58f639
<Click to see difference>
FYI: You should be able to reduce the test setup to:
// #ExtendWith(SpringExtension.class) already comes with #DataJpaTest
#DataJpaTest
// #ContextConfiguration
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class InventoryRepositoryTest {

System.ArgumentException: 24100: The spatial reference identifier (SRID) is not valid. SRIDs must be between 0 and 999999

I want to save a new geometry data at database, but I'm receiving this error message all the time.
A .NET Framework error occurred during execution of user-defined routine or aggregate "geometry".
System.ArgumentException: 24100: The spatial reference identifier (SRID) is not valid. SRIDs must be between 0 and 999999.
Logging
2019-10-02 06:00:41.009 DEBUG 55688 --- [on(2)-127.0.0.1] o.h.e.j.e.i.JdbcEnvironmentInitiator : Database ->
name : Microsoft SQL Server
version : 14.00.1000
major : 14
minor : 0
2019-10-02 06:00:41.010 DEBUG 55688 --- [on(2)-127.0.0.1] o.h.e.j.e.i.JdbcEnvironmentInitiator : Driver ->
name : Microsoft JDBC Driver 7.4 for SQL Server
version : 7.4.1.0
major : 7
minor : 4
2019-10-02 06:00:41.010 DEBUG 55688 --- [on(2)-127.0.0.1] o.h.e.j.e.i.JdbcEnvironmentInitiator : JDBC version : 4.2
2019-10-02 06:00:41.054 INFO 55688 --- [on(2)-127.0.0.1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.spatial.dialect.sqlserver.SqlServer2008SpatialDialect
...
2019-10-02 05:50:22.232 DEBUG 62340 --- [nio-8080-exec-6] org.hibernate.SQL : insert into teste_geo (geom, nome) values (?, ?)
Hibernate: insert into teste_geo (geom, nome) values (?, ?)
2019-10-02 05:50:22.232 TRACE 62340 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARBINARY] - [POLYGON ((4 0, 2 2, 4 4, 6 2, 4 0))]
2019-10-02 05:50:22.232 TRACE 62340 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARCHAR] - [5f230d1b-ad0d-44a8-997e-02f4533bcfcd]
2019-10-02 05:50:26.452 INFO 62340 --- [ scheduling-1] c.v.g.o.service.ExemploService : Executou chamada do servico!
2019-10-02 05:50:26.452 WARN 62340 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 6522, SQLState: S0001
My class code
import lombok.Getter;
import lombok.Setter;
import org.locationtech.jts.geom.Geometry;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "TESTE_GEO")
#Getter
#Setter
public class TesteGeom {
#Id
#Column(name = "nome")
private String name;
#Column(name = "geom")
private Geometry geometry;
}
...........
UUID idUnique = UUID.randomUUID();
TesteGeom t = new TesteGeom();
t.setName(idUnique.toString());
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel() ,4326);
Coordinate[] coords =
new Coordinate[] {new Coordinate(4, 0), new Coordinate(2, 2),
new Coordinate(4, 4), new Coordinate(6, 2), new Coordinate(4, 0) };
LinearRing ring = geometryFactory.createLinearRing( coords );
LinearRing holes[] = null; // use LinearRing[] to represent holes
int SRID = geometryFactory.getSRID();
Polygon polygon = geometryFactory.createPolygon(ring, holes );
t.setGeometry(polygon);
t.getGeometry().setSRID(4326);
Executing the same SQL on management studio it works!
insert into teste_geo (geom, nome) values ('POLYGON ((4 0, 2 2, 4 4, 6 2, 4 0))', 'OK');
nome varchar(50)
geom geometry
In a query I got the error. Probably there are some dialect error.
org.springframework.orm.jpa.JpaSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:351)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
I found the solution.
At my model I was using:
import org.locationtech.jts.geom.Geometry;
But Hibernate Spatial only accept :
import com.vividsolutions.jts.geom.Geometry;
So, I change my lib and everything work.

#RestController - Collection issue

I am implementing a spring boot application using #RestController w/ Angular.js client and I want to create/update a Group with one or multiple Users (as children). This does not work with multiple users.
Model Signature:
Grp {
externalId (string, optional),
grpOwner (User, optional),
grpTxt (string, optional),
users (Array[User], optional)
}
User {
externalId (string, optional),
username (string, optional)
}
grp.json (both users exist in database)
{
"externalId": "G0000001",
"users": [
{
"username": "admin"
},
{
"username": "system"
}
]
})
When trying to create/update one Group w/ multiple users, only the first one is taken into consideration. Actually, when debugging the Java part. Any idea?
#RequestMapping(method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public ResponseEntity<Grp> updateGrp(#RequestBody Grp grp) throws URISyntaxException {
log.debug("REST request to update Grp : {}", grp);
// Check if the group has been created
Optional<Grp> oGrp = gDao.findOneByExternalIdAndGrpOwner(grp.getExternalId(), this.getCurrentUser());
if (oGrp.isPresent()) {
Grp mGrp = oGrp.get();
this.merge(mGrp, grp);
Grp result = gDao.save(mGrp);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert("grp", grp.getExternalId().toString()))
.body(result);
}
return createGrp(grp);
}
Trace:
2016-07-06 11:29:12.563 DEBUG 3216 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing PUT request for [/api/grps]
2016-07-06 11:29:12.566 DEBUG 3216 --- [nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /api/grps
2016-07-06 11:29:12.567 DEBUG 3216 --- [nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity<com.coopyrightcode.common.domain.Grp> com.coopyrightcode.common.web.rest.GrpResource.updateGrp(com.coopyrightcode.common.domain.Grp) throws java.net.URISyntaxException]
2016-07-06 11:29:12.604 DEBUG 3216 --- [nio-8080-exec-5] m.m.a.RequestResponseBodyMethodProcessor : Read [class com.coopyrightcode.common.domain.Grp] as "application/json;charset=UTF-8" with [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#4982ce48]
2016-07-06 11:29:12.613 DEBUG 3216 --- [nio-8080-exec-5] c.c.common.aop.logging.LoggingAspect : Enter: com.coopyrightcode.common.web.rest.GrpResource.updateGrp() with argument[s] = [Grp [grpTxt=null, grpOwner=null, users=[User [username=admin, password=null, fName=null, lName=null, email=null, activated=false, langKey=null, appKey=63d71c52-95cd-43db-9, resetKey=3dfaf9f7-b46d-4daf-9, resetDate=null, usrAccountNonLocked=true, usrAccountNonExpired=true, usrCredentialsNonExpired=true, usrBio=null, usrMobile=null, usrPhone=null, usrPics=null, usrReferent=null, usrCtrId=null]]]]
2016-07-06 11:29:12.613 DEBUG 3216 --- [nio-8080-exec-5] c.c.common.web.rest.PortfolioResource : REST request to update Grp : Grp [grpTxt=null, grpOwner=null, users=[User [username=admin, password=null, fName=null, lName=null, email=null, activated=false, langKey=null, appKey=63d71c52-95cd-43db-9, resetKey=3dfaf9f7-b46d-4daf-9, resetDate=null, usrAccountNonLocked=true, usrAccountNonExpired=true, usrCredentialsNonExpired=true, usrBio=null, usrMobile=null, usrPhone=null, usrPics=null, usrReferent=null, usrCtrId=null]]]

How to pause a Camel Quartz2 timer in a suspended route?

The following unit test tries a quartz2 route that triggers each second:
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
public class CamelQuartzTest extends CamelTestSupport {
static private String routeId = "test-route";
#Test
public void testSuspendRoute() throws Exception {
// arrange
MockEndpoint mock = getMockEndpoint("mock:result");
// act
System.out.println("context.start()");
context.start();
Thread.sleep(2000);
System.out.println(String.format("receivedCounter = %d", mock.getReceivedCounter()));
System.out.println("context.startRoute()");
context.startRoute(routeId);
Thread.sleep(2000);
System.out.println(String.format("receivedCounter = %d", mock.getReceivedCounter()));
System.out.println("context.suspendRoute()");
context.suspendRoute(routeId);
Thread.sleep(2000);
System.out.println(String.format("receivedCounter = %d", mock.getReceivedCounter()));
System.out.println("context.resumeRoute()");
context.resumeRoute(routeId);
Thread.sleep(2000);
System.out.println(String.format("receivedCounter = %d", mock.getReceivedCounter()));
System.out.println("context.stop()");
context.stop();
System.out.println(String.format("receivedCounter = %d", mock.getReceivedCounter()));
// assert
assertEquals(4, mock.getReceivedCounter());
}
#Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("quartz2://testtimer?cron=0/1+*+*+?+*+*")
.autoStartup(false)
.routeId(routeId)
.setBody()
.simple("${header.triggerName}: ${header.fireTime}")
.to("mock:result", "stream:out");
}
};
}
}
Result output:
context.start()
receivedCounter = 0
context.startRoute()
testtimer: Tue Oct 21 10:06:38 CEST 2014
testtimer: Tue Oct 21 10:06:39 CEST 2014
receivedCounter = 2
context.suspendRoute()
receivedCounter = 2
context.resumeRoute()
testtimer: Tue Oct 21 10:06:41 CEST 2014
testtimer: Tue Oct 21 10:06:41 CEST 2014
testtimer: Tue Oct 21 10:06:42 CEST 2014
testtimer: Tue Oct 21 10:06:43 CEST 2014
receivedCounter = 6
context.stop()
receivedCounter = 6
After resuming the route, the result shows 4 incoming triggers, while 2 were expected. Apparently, the quartz2 timer keeps firing while the route is suspended. How can I make quartz2 take a pause while the route is suspended?
Found the root cause: if a quartz job is suspended for a while, and resumed again, the default behavior of quartz is to catch up the triggers, aka "misfires", that were missed during the suspended period. I did not find a way the switch off this misfire behavior. However, decreasing the misfire threshold from 60 seconds to 500 ms helped in my case. This can be done by copying the default quartz.properties from quartz-<version>.jar to org/quartz/quartz.properties in the default classpath, and overrule the misfire threshold:
# Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance.
# This file overrules the default quartz.properties file in the
# quartz-<version>.jar
#
org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 10
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
# default threshold: 60 seconds
#org.quartz.jobStore.misfireThreshold: 60000
# overruled threshold: 500 ms, to prevent superfluous triggers after resuming
# a quartz job
org.quartz.jobStore.misfireThreshold: 500
org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore

Eager loading in Hibernate doesnt work, referenced attrribute has null values

i have a hibernate problem, probably due to lazy/eager loading or something similiar. I have a model class student and a model class century.
The student has an attribute century. Before I save the stdent in the dao i save the referenced century. But when I save the student, the century is null everywhere, except for it's name.
I tried
#Fetch(FetchMode.JOIN),
#ManyToOne(fetch = FetchType.EAGER) and getHibernateTemplate().initialize(student.getCentury());
so far but nothing will work.
Some ideas would be great, thanks in advance!
Student class:
// #Fetch(FetchMode.JOIN)
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "CENTURY_ID")
public Century getCentury() {
return century;
}
StudentDao:
load-method inherited from SuperDao:
#SuppressWarnings("unchecked")
public T load(Long id) {
T object = (T) getSession().get(
classOfData, id);
log.error(String.format("%s with id %d loaded.", CLASS_NAME_OF_DATA, id));
if (object == null) {
log.error("Object not found");
}
return object;
}
save method in StudentDao:
#Override
public Student save(Student student) throws HibernateException {
// getHibernateTemplate().initialize(student.getCentury());
log.error("Saving student:" + student.toString());
Century century = centuryDao.load(student.getCentury().getId());
System.out.println("instudentdao:" + century.getManiple());
centuryDao.save(student.getCentury());
getSession().saveOrUpdate(student);
log.error(String.format("Student with id %d saved.", student.getId()));
return student;
}
StudentAction load method is passed down to Dao:
private void loadStudent(String id) {
create = request.getParameter("mode").equals("create");
edit = request.getParameter("mode").equals("edit");
view = request.getParameter("mode").equals("view");
if (request.getParameter("mode").equals("create"))
student = new Student();
else
student = studentService.load(Long.valueOf(id));
}
log for (fetch = FetchType.EAGER)
2013-11-17 13:15:59,819 ERROR http-bio-8080-exec-9 - <Saving student:Student [id=1, firstName=hans, lastName=wurst, gender=null, city=HAMBURG, postalCode=22123, street=SHEMALESTREET, streetNumber=23, company=Company [id=null, name1=OLE, name2=null, nameShort=null, city=null, postalCode=null, street=null, streetNumber=null, email=null, phone=null, fax=null, status=null, supervisors=null], phone=1234123, email=olko#olko.olko, century=Century [id=null, name=Zenturie, maniple=null, students=null], birthday=Sun Jan 01 00:00:00 CET 2012, birthPlace=MUELLTONNE, userId=123, addressAddition=, status=ACTIVE, supervisor=Supervisor [id=null, firstName=null, lastName=, company=null, email=null, phone=null]]>
log for #JoinColumn(name = "CENTURY_ID")
2013-11-17 13:22:25,266 ERROR http-bio-8080-exec-10 - <Saving student:Student [id=1, firstName=hans, lastName=wurst, gender=null, city=HAMBURG, postalCode=22123, street=SHEMALESTREET, streetNumber=23, company=Company [id=null, name1=OLE, name2=null, nameShort=null, city=null, postalCode=null, street=null, streetNumber=null, email=null, phone=null, fax=null, status=null, supervisors=null], phone=1234123, email=olko#olko.olko, century=Century [id=null, name=Zenturie, maniple=null, students=null], birthday=Sun Jan 01 00:00:00 CET 2012, birthPlace=MUELLTONNE, userId=123, addressAddition=, status=ACTIVE, supervisor=Supervisor [id=null, firstName=null, lastName=, company=null, email=null, phone=null]]>
log for initialize()
2013-11-17 13:25:01,381 ERROR http-bio-8080-exec-10 - <Saving student:Student [id=1, firstName=hans, lastName=wurst, gender=null, city=HAMBURG, postalCode=22123, street=SHEMALESTREET, streetNumber=23, company=Company [id=null, name1=OLE, name2=null, nameShort=null, city=null, postalCode=null, street=null, streetNumber=null, email=null, phone=null, fax=null, status=null, supervisors=null], phone=1234123, email=olko#olko.olko, century=Century [id=null, name=Zenturie, maniple=null, students=null], birthday=Sun Jan 01 00:00:00 CET 2012, birthPlace=MUELLTONNE, userId=123, addressAddition=, status=ACTIVE, supervisor=Supervisor [id=null, firstName=null, lastName=, company=null, email=null, phone=null]]>

Resources