No converter found capable of converting GeoCommand to DBObject - java

I am unable to query a GeoSpatial Query of within in spring data mongodb, whether I write a custom query or spring data interface query I am getting this error and the same query is working fine from mongodb client(robomongo):
Following is the Query:
distanceRepository.findDistanceBySrcWithin(srcCircle);
Below is the mongo configurations:
#Override
public MongoClient mongo() throws Exception {
List<MongoCredential> mongoCredentials = new ArrayList<>();
mongoCredentials.add(MongoCredential.createCredential(userName, "admin", password.toCharArray()));
return new MongoClient(new ServerAddress(host, port), mongoCredentials);
}
#Override
#Bean
public MongoTemplate mongoTemplate() throws Exception {
MultiTenantMongoDbFactory mongoDbFactory = (MultiTenantMongoDbFactory) mongoDbFactory();
MongoTypeMapper typeMapper = new DefaultMongoTypeMapper(null);
MappingMongoConverter converter = new MappingMongoConverter(mongoDbFactory(), new MongoMappingContext());
converter.setTypeMapper(typeMapper);
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, converter);
mongoDbFactory.setMongoTemplate(mongoTemplate);
return mongoTemplate;
}
#Override
#Bean
public MongoDbFactory mongoDbFactory() throws Exception {
return new MultiTenantMongoDbFactory(mongo(), dbName);
}
Following is the stack trace:
2017-09-12 15:51:00 ERROR [JobDurationServiceImpl]:250 - Error in method getDistance Reason: No converter found capable of converting from type [org.springframework.data.mongodb.core.query.GeoCommand] to type [com.mongodb.DBObject]
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.mongodb.core.query.GeoCommand] to type [com.mongodb.DBObject]
at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:313)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:195)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:176)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.convertToMongoType(MappingMongoConverter.java:979)
at org.springframework.data.mongodb.core.convert.QueryMapper.delegateConvertToMongoType(QueryMapper.java:393)
at org.springframework.data.mongodb.core.convert.QueryMapper.convertSimpleOrDBObject(QueryMapper.java:381)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedValue(QueryMapper.java:327)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedKeyword(QueryMapper.java:277)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedObjectForField(QueryMapper.java:215)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedObject(QueryMapper.java:130)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1760)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1750)
at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:624)
at org.springframework.data.mongodb.repository.query.MongoQueryExecution$CollectionExecution.execute(MongoQueryExecution.java:70)
at org.springframework.data.mongodb.repository.query.MongoQueryExecution$ResultProcessingExecution.execute(MongoQueryExecution.java:345)
at org.springframework.data.mongodb.repository.query.AbstractMongoQuery.execute(AbstractMongoQuery.java:91)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy76.findDistanceBySrcWithin(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

The key is to add the below line:
converter.afterPropertiesSet();
after
MappingMongoConverter converter = new MappingMongoConverter(mongoDbFactory(),
new MongoMappingContext());
converter.setTypeMapper(typeMapper);
while creating MongoTemplate

Related

java.util.List.iterator() is no accessor method

When I am trying to access, List method iterator() i am getting below exception:
java.lang.IllegalArgumentException: Invoked method public abstract java.util.Iterator java.util.List.iterator() is no accessor method!
at org.springframework.util.Assert.notNull(Assert.java:115) ~[spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.data.projection.MapAccessingMethodInterceptor$Accessor.<init>(MapAccessingMethodInterceptor.java:97) ~[spring-data-commons-1.12.6.RELEASE.jar:na]
at org.springframework.data.projection.MapAccessingMethodInterceptor.invoke(MapAccessingMethodInterceptor.java:62) ~[spring-data-commons-1.12.6.RELEASE.jar:na]
at org.springframework.data.projection.ProjectingMethodInterceptor.invoke(ProjectingMethodInterceptor.java:75) ~[spring-data-commons-1.12.6.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.data.projection.ProxyProjectionFactory$TargetAwareMethodInterceptor.invoke(ProxyProjectionFactory.java:218) ~[spring-data-commons-1.12.6.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.5.RELEASE.jar:4.3.5.RELEASE]
Code snippet below:
#RequestMapping (value = "/{field}", method = RequestMethod.PATCH, produces = "application/json")
#ResponseBody
public void applyPatchRequest(#PathVariable String field ,JsonArray operations) {
LookupPatchDto lookupPatchDto = new LookupPatchDto();
lookupPatchDto.setField(field);
lookupPatchDto.setVals(lookupValsService.getAllByField(field));
final JsonPatch patch = Json.createPatch(operations);
final JsonObject result = patch.apply(lookupPatchConverter.toJson(lookupPatchDto));
lookupPatchDto = lookupPatchConverter.fromJson(result);
lookupValsService.save(lookupPatchDto.getVals());
}
I am getting error on below line while applying apply function.
final JsonObject result = patch.apply(lookupPatchConverter.toJson(lookupPatchDto));

Spring Batch Partitioning inject stepExecutionContext parameter in itemReader

I am trying to learn Spring Batch with Partitioner.
The issue is that I need to set the filenames dynamically from the Partitioner implementation. And I am trying to get it in the itemReader. But it gives filename null.
My Spring Batch configuration:
#Bean
#StepScope
public ItemReader<Transaction> itemReader(#Value("#{stepExecutionContext[filename]}") String filename)
throws UnexpectedInputException, ParseException {
FlatFileItemReader<Transaction> reader = new FlatFileItemReader<Transaction>();
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
String[] tokens = { "username", "userid", "transactiondate", "amount" };
tokenizer.setNames(tokens);
reader.setResource(new ClassPathResource(
"input/"+filename));
DefaultLineMapper<Transaction> lineMapper = new DefaultLineMapper<Transaction>();
lineMapper.setLineTokenizer(tokenizer);
lineMapper.setFieldSetMapper(new RecordFieldSetMapper());
reader.setLinesToSkip(1);
reader.setLineMapper(lineMapper);
return reader;
}
#Bean(name = "partitioningJob")
public Job partitioningJob() throws UnexpectedInputException, MalformedURLException, ParseException {
return jobs.get("partitioningJob").listener(jobListener()).start(partitionStep()).build();
}
#Bean
public Step partitionStep() throws UnexpectedInputException, MalformedURLException, ParseException {
return steps.get("partitionStep").partitioner(step2()).partitioner("step2", partitioner()).gridSize(2).taskExecutor(taskExecutor).build();
}
#Bean
public Step step2() throws UnexpectedInputException, MalformedURLException, ParseException {
return steps.get("step2").<Transaction, Transaction> chunk(1).reader(itemReader(null)).processor(itemProcessor()).writer(itemWriter(marshaller(),null)).build();
}
#Bean
public TransactionPartitioner partitioner() {
TransactionPartitioner partitioner = new TransactionPartitioner();
return partitioner;
}
#Bean
public JobListener jobListener() {
return new JobListener();
}
#Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setMaxPoolSize(2);
taskExecutor.setQueueCapacity(2);
taskExecutor.setCorePoolSize(2);
taskExecutor.afterPropertiesSet();
return taskExecutor;
}
And my TransactionPartitioner class is:
public class TransactionPartitioner implements Partitioner {
public Map<String, ExecutionContext> partition(int range) {
Map<String, ExecutionContext> result = new HashMap<String, ExecutionContext>();
for (int i = 1; i <= range; i++) {
ExecutionContext exContext = new ExecutionContext();
exContext.put("filename", "input"+i+".csv");
exContext.put("name", "Thread" + i);
result.put("partition" + i, exContext);
}
return result;
}
}
Is this not the right way to do it? Please suggest.
This is the stack trace:
18:23:39.060 [main] DEBUG org.springframework.batch.core.job.AbstractJob - Upgrading JobExecution status: StepExecution: id=1, version=2, name=partitionStep, status=FAILED, exitStatus=FAILED, readCount=0, filterCount=0, writeCount=0 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=0, rollbackCount=0, exitDescription=org.springframework.batch.core.JobExecutionException: Partition handler returned an unsuccessful step
at org.springframework.batch.core.partition.support.PartitionStep.doExecute(PartitionStep.java:112)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:200)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148)
at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:392)
at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128)
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.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy19.run(Unknown Source)
at org.baeldung.spring_batch_intro.App.main(App.java:24)
; org.springframework.batch.item.ItemStreamException: Failed to initialize the reader
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:147)
at org.springframework.batch.item.support.CompositeItemStream.open(CompositeItemStream.java:96)
at org.springframework.batch.core.step.tasklet.TaskletStep.open(TaskletStep.java:310)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:197)
at org.springframework.batch.core.partition.support.TaskExecutorPartitionHandler$1.call(TaskExecutorPartitionHandler.java:139)
at org.springframework.batch.core.partition.support.TaskExecutorPartitionHandler$1.call(TaskExecutorPartitionHandler.java:136)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Input resource must exist (reader is in 'strict' mode): class path resource [input/null]
at org.springframework.batch.item.file.FlatFileItemReader.doOpen(FlatFileItemReader.java:251)
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:144)
... 9 more
As per #Sabir's suggestion, I checked my data. The step context table looks like this:
| STEP_EXECUTION_ID | SHORT_CONTEXT | SERIALIZED_CONTEXT |
| 1 | {"map":[{"entry":[{"string":"SimpleStepExecutionSplitter.GRID_SIZE","long":2},{"string":["batch.stepType","org.springframework.batch.core.partition.support.PartitionStep"]}]}]} | NULL
| 2 | {"map":[{"entry":[{"string":["filename","input2.csv"]},{"string":["name","Thread2"]}]}]} | NULL |
| 3 | {"map":[{"entry":[{"string":["filename","input1.csv"]},{"string":["name","Thread1"]}]}]}
Here is the full code for it: https://drive.google.com/file/d/0Bziay9b2ceLbUXdTRnZoSjRfR2s/view?usp=sharing
Went through your code and tried to run it.
Currently it is not binding the file name at scope level.
You have two configuration files:
SpringConfig - containing Spring related config beans
SpringBatchConfig - containing Spring batch related beans
The first one contains the annotation #EnableBatchProcessing and #Configuration.
But the itemReader is defined in another config file which do not contain any of the annotations.
You should have #Configuration on the other file too.
OR
You can add both the annotations to SpringBatchConfig config file and can skip them in Spring
Without this, these configurations are not read properly and the itemReader is not considered as Step Scoped (i.e. the annotation #StepScope does not work) and does not bind the values at step level, and hence you are getting the NULL values.
Its not application code's responsibility to call partition method like you are doing in below ,
#Bean
public TransactionPartitioner partitioner() {
TransactionPartitioner partitioner = new TransactionPartitioner();
partitioner.partition(10);
return partitioner;
}
Framework will call partition method for you. You simply need to return Partitioner without calling partition(10) method explicitly.
Having said that , you need to set partitioner gridSize in partitioner step as shown below,
#Bean
public Step partitionStep() throws UnexpectedInputException, MalformedURLException, ParseException {
return steps.get("partitionStep").partitioner(step2()).partitioner("step2", partitioner()).gridSize(10).taskExecutor(taskExecutor).build();
}
Above points might be root cause for your issue. Rest of the things seem OK with your code.

SpringBoot 1.5.3 createStoredProcedureQuery not accepting Null parameters

While using SpringBoot with MSSQL server stored proc, when the value is null, Stored proc fails to execute. the value have default as null while calling.
If the parameters are excluded, the proc works. But as these are optional parameters, what are my options to call the stored proc?
When i try to pass null while calling the stored procedure, it is failing with this error.
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: Error calling CallableStatement.getMoreResults; SQL [saveInfo]; nested exception is org.hibernate.exception.SQLGrammarException: Error calling CallableStatement.getMoreResults] with root cause
java.sql.SQLException: Parameter #1 has not been set.
at net.sourceforge.jtds.jdbc.TdsCore.executeSQL(TdsCore.java:1049)
at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQL(JtdsStatement.java:563)
at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.execute(JtdsPreparedStatement.java:787)
at org.hibernate.result.internal.OutputsImpl.<init>(OutputsImpl.java:52)
at org.hibernate.procedure.internal.ProcedureOutputsImpl.<init>(ProcedureOutputsImpl.java:32)
at org.hibernate.procedure.internal.ProcedureCallImpl.buildOutputs(ProcedureCallImpl.java:411)
at org.hibernate.procedure.internal.ProcedureCallImpl.getOutputs(ProcedureCallImpl.java:363)
at org.hibernate.jpa.internal.StoredProcedureQueryImpl.outputs(StoredProcedureQueryImpl.java:234)
at org.hibernate.jpa.internal.StoredProcedureQueryImpl.execute(StoredProcedureQueryImpl.java:217)
at com.tda.etfmc.service.repository.ETFMgmtRepository.saveCommissionFreeETF(ETFMgmtRepository.java:87)
at com.tda.etfmc.service.repository.ETFMgmtRepository$$FastClassBySpringCGLIB$$d1d68142.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
StoredProc:
CREATE PROCEDURE [dbo].[saveInfo]
#input1 varchar(16) = NULL,
#input2 varchar(16) = NULL
AS
BEGIN
//do save here
END
GO
#Repository
public class MyRepository {
private EntityManager entityManager;
public MyRepository(EntityManager entityManager) {
this.entityManager = entityManager;
}
#Procedure(name = "saveInfo")
#Transactional
public void saveInfo(List<Input> inputList) throws SQLException {
StoredProcedureQuery saveInfo;
for (Input input : inputList) {
saveInfo = entityManager.createNamedStoredProcedureQuery("saveInfo");
saveInfo.setParameter("input1", input.getInput1());// pass null here
saveInfo.setParameter("input2", input.getInput2());
saveInfo.execute();
}
}
}
#Data
#NamedStoredProcedureQuery(name = "saveInfo", procedureName = "saveInfo", parameters = {
#StoredProcedureParameter(name = "input1", type = String.class, mode = ParameterMode.IN),
#StoredProcedureParameter(name = "input2", type = String.class, mode = ParameterMode.IN) })
class Input implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "#input1")
private String input1;
#Column(name = "#input2")
private String input2;
}

Need to call StoredProcedure in jave using Hibernate

Just want to call Stored procedure of SQL server from java using Hibernate as ORM.
The stored Procedure has so many result set which I am keeping it in Java as DTO's and each one as list in one DTO to send as JSON payload for Front-end integration.
But I am getting exception saying"org.hibernate.MappingException: Unknown entity: com.test.plans.dto.TemplatesDTO"
public ItemDetailsDTO getItemDetails(int no) {
Session session = getSession();
Connection connection = null;
List<ItemDetailsDTO> resultList = new ArrayList<>();
try {
ResultSet rs = null;
SessionImpl sessionImpl = (SessionImpl) session;
connection = sessionImpl.connection();
Query query = session.createSQLQuery("exec usp_GetItemDetails :no")
.addEntity(TemplatesDTO.class)
.setParameter("no", no);
resultList = query.list();
} catch (Exception e) {
System.out.println("error");
e.printStackTrace();
}
return resultList.get(0);
}
DTO :
import java.util.List;
public class ItemDetailsDTO {
private List<TemplatesDTO> templates;
public List<TemplatesDTO> gettemplates() {
return templates;
}
public void settemplates(List<TemplatesDTO> templates) {
this.templates = templates;
}
}
Please find below complete trace of exception
org.hibernate.MappingException: Unknown entity: com.test.plans.dto.TemplatesDTO
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:783)
at org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.getSQLLoadable(SQLQueryReturnProcessor.java:358)
at org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.processRootReturn(SQLQueryReturnProcessor.java:411)
at org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.processReturn(SQLQueryReturnProcessor.java:378)
at org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.process(SQLQueryReturnProcessor.java:180)
at org.hibernate.loader.custom.sql.SQLCustomQuery.(SQLCustomQuery.java:71)
at org.hibernate.engine.query.internal.NativeQueryInterpreterStandardImpl.createQueryPlan(NativeQueryInterpreterStandardImpl.java:70)
at org.hibernate.engine.query.spi.QueryPlanCache.getNativeSQLQueryPlan(QueryPlanCache.java:210)
at org.hibernate.internal.AbstractSessionImpl.getNativeSQLQueryPlan(AbstractSessionImpl.java:306)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:322)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
at nbcu.compass.contingencyplans.dao.impl.ContDAOImpl.getItemDetails(ContingencyDAOImpl.java:503)
at nbcu.compass.contingencyplans.dao.impl.ContDAOImpl$$FastClassBySpringCGLIB$$c2b97106.invoke()
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at com.test.plans.dao.impl.ContDAOImpl$$EnhancerBySpringCGLIB$$a1741e1f.getItemDetails()
at com.test.plans.service.impl.ContPlanServiceImpl.getConditionScheduleItemDetails(ContingencyPlanServiceImpl.java:316)
at test.plans.plans.rest.impl.PlanResourceImpl.getItemDetails(PlanResourceImpl.java:87)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)

Specifying custom persistence unit in spring boot

I have the following configuration in my spring boot application:
#Bean(name="entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
#Value("${ds.fake.driverClass}") String driverClass,
#Value("${ds.fake.url}") String url,
#Value("${ds.fake.user}") String user,
#Value("${ds.fake.password}") String password,
#Value("${ds.fake.hibernateDialect}") String hibernateDialect){
LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
// bean.setPersistenceUnitName("fake");
bean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
bean.setPersistenceUnitManager(persistenceUnitManager(driverClass,url,user,password));
bean.setJpaVendorAdapter(adapter());
bean.setJpaProperties((Properties)fakeJpaProperties(hibernateDialect).get());
bean.setDataSource(fakeDataSource(driverClass,url,user,password));
//bean.setPackagesToScan("my.required.package");
bean.afterPropertiesSet();
return bean;
}
#Bean
public MergingPersistenceUnitManager persistenceUnitManager(
#Value("${ds.fake.driverClass}") String driverClass,
#Value("${ds.fake.url}") String url,
#Value("${ds.fake.user}") String user,
#Value("${ds.fake.password}") String password){
MergingPersistenceUnitManager merger = new MergingPersistenceUnitManager();
// merger.setPersistenceXmlLocations("classpath*:META-INF/fake/persistence.xml");
merger.setPackagesToScan("my.required.package");
// merger.setDefaultDataSource(fakeDataSource(driverClass,url,user,password));
return merger;
}
#Bean
public HibernateJpaVendorAdapter adapter(){
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setGenerateDdl(false);
return adapter;
}
#Bean(initMethod="init",destroyMethod="close")
public static PoolingDataSource fakeDataSource(
#Value("${ds.fake.driverClass}") String driverClass,
#Value("${ds.fake.url}") String url,
#Value("${ds.fake.user}") String user,
#Value("${ds.fake.password}") String password) {
PoolingDataSource bean = new PoolingDataSource();
bean.setClassName("bitronix.tm.resource.jdbc.lrc.LrcXADataSource");
bean.setUniqueName("fakeDataSource");
bean.setMinPoolSize(2);
bean.setMaxPoolSize(10);
bean.setMaxIdleTime(900);
bean.setUseTmJoin(true);
bean.setDeferConnectionRelease(true);
bean.setAutomaticEnlistingEnabled(true);
bean.setAllowLocalTransactions(true);
bean.setIsolationLevel("READ_COMMITTED");
Properties props = new Properties();
props.setProperty("driverClassName", driverClass);
props.setProperty("url", url);
props.setProperty("user", user);
props.setProperty("password", password);
bean.setDriverProperties(props);
return bean;
}
If i start up my application I am getting the following error:
Caused by: java.lang.IllegalStateException: Persistence unit with name 'default' already obtained
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.obtainPersistenceUnitInfo(DefaultPersistenceUnitManager.java:678)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.determinePersistenceUnitInfo(LocalContainerEntityManagerFactoryBean.java:355)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:307)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1613)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)
... 21 more
However, If i Try to uncomment the line bean.setPersistenceUnitName("fake"); , I get the new error:
Caused by: java.lang.IllegalArgumentException: No persistence unit with name 'fake' found
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.obtainPersistenceUnitInfo(DefaultPersistenceUnitManager.java:674)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.determinePersistenceUnitInfo(LocalContainerEntityManagerFactoryBean.java:355)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:307)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at com.ixaris.providers.fake.app.boot.FakeAppBooter.entityManagerFactory(FakeAppBooter.java:226)
at com.ixaris.providers.fake.app.boot.FakeAppBooter$$EnhancerBySpringCGLIB$$6ec884df.CGLIB$entityManagerFactory$2(<generated>)
at com.ixaris.providers.fake.app.boot.FakeAppBooter$$EnhancerBySpringCGLIB$$6ec884df$$FastClassBySpringCGLIB$$cefb3e29.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at com.ixaris.providers.fake.app.boot.FakeAppBooter$$EnhancerBySpringCGLIB$$6ec884df.entityManagerFactory(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 24 more
How can I go around this / maybe "create" the persistence unit myself?

Categories