NoSuchMethodException in JDBI while using it with Kotlin - postgresql

I am trying to use JDBI with PostgreSQL database. I am using Kotlin. Even after trying for several hours, I couldn't get to a point where I can use basic CRUD operations.
val users = jdbi.withHandleUnchecked {
it
.createQuery("select id, name from users")
.mapToBean(User::class.java)
.list()
}
Here is the code I am using. (There is no issue with the connection. I have verified that by executing queries using JDBC)
Here is the model class,
data class User(val id: Int, val name: String)
Here is the exception I am getting,
Exception in thread "main" java.lang.NoSuchMethodException: no such constructor: User.<init>()void/newInvokeSpecial
at java.base/java.lang.invoke.MemberName.makeAccessException(MemberName.java:961)
at java.base/java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:1101)
at java.base/java.lang.invoke.MethodHandles$Lookup.resolveOrFail(MethodHandles.java:2030)
at java.base/java.lang.invoke.MethodHandles$Lookup.findConstructor(MethodHandles.java:1264)
at org.jdbi.v3.core.mapper.reflect.internal.BeanPropertiesFactory$BeanPojoProperties$PropertiesHolder.<init>(BeanPropertiesFactory.java:202)
at org.jdbi.v3.core.config.JdbiCaches.lambda$declare$0(JdbiCaches.java:49)
at org.jdbi.v3.core.config.JdbiCaches$1.lambda$get$1(JdbiCaches.java:63)
at java.base/java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1705)
at org.jdbi.v3.core.config.JdbiCaches$1.get(JdbiCaches.java:63)
at org.jdbi.v3.core.mapper.reflect.internal.BeanPropertiesFactory$BeanPojoProperties.getProperties(BeanPropertiesFactory.java:81)
at org.jdbi.v3.core.mapper.reflect.internal.PojoMapper.specialize0(PojoMapper.java:99)
at org.jdbi.v3.core.mapper.reflect.internal.PojoMapper.specialize(PojoMapper.java:80)
at org.jdbi.v3.core.result.ResultSetResultIterator.<init>(ResultSetResultIterator.java:38)
at org.jdbi.v3.core.result.ResultIterable.lambda$of$0(ResultIterable.java:54)
at org.jdbi.v3.core.result.ResultIterable.stream(ResultIterable.java:228)
at org.jdbi.v3.core.result.ResultIterable.collect(ResultIterable.java:284)
at org.jdbi.v3.core.result.ResultIterable.list(ResultIterable.java:273)
at MainKt$main$$inlined$withHandleUnchecked$1.withHandle(Jdbi858Extensions.kt:185)
at org.jdbi.v3.core.Jdbi.withHandle(Jdbi.java:342)
at MainKt.main(Main.kt:26)
at MainKt.main(Main.kt)
Caused by: java.lang.NoSuchMethodError: User: method 'void <init>()' not found
at java.base/java.lang.invoke.MethodHandleNatives.resolve(Native Method)
at java.base/java.lang.invoke.MemberName$Factory.resolve(MemberName.java:1070)
at java.base/java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:1098)
... 19 more
Process finished with exit code 1
Seemingly it has something to do with the User class. So, I tried tinkering with it.
Where is what I tried, (changed to var from val)
data class User(var id: Int, var name: String)
The exception being thrown is the same as above.
Here is how the dependency section of my gradle.build looks like,
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.5.31'
implementation 'org.postgresql:postgresql:42.3.0'
implementation 'org.jdbi:jdbi3-kotlin-sqlobject:3.23.0'
implementation 'com.zaxxer:HikariCP:5.0.0'
implementation 'org.slf4j:slf4j-jdk14:1.7.32'
}
Any assistance would be really helpful.

Related

Migration from Hibernate 5 to 6

I am trying to migrate a spring boot 2.3 application running on java 8 to spring boot 3 java 17. The issue is in a repository.
It has a query method as follows:
#Query(value = "SELECT ca FROM CorporateActionsV2 ca WHERE ( ca.dividendAmount, TO_CHAR(TO_DATE(ca.effectiveDate) - 5,'IYYY'), TO_CHAR(TO_DATE(ca.effectiveDate) - 5,'IW'), ca.tickerSerial) IN (SELECT c.dividendAmount, TO_CHAR(TO_DATE(c.effectiveDate) - 5,'IYYY'), TO_CHAR(TO_DATE(c.effectiveDate) - 5,'IW'), c.tickerSerial FROM CorporateActionsV2 c WHERE c.dividendAmount IS NOT NULL AND c.eventLabel = 'Dividend' AND c.actionStatus != 'Deleted'" +
" GROUP BY c.dividendAmount, TO_CHAR(TO_DATE(c.effectiveDate) - 5,'IYYY'), TO_CHAR(TO_DATE(c.effectiveDate) - 5,'IW'), c.tickerSerial HAVING COUNT(*) > 1 )")
List<CorporateActionsV2> getDuplicateActions();
The entity CorporateActionsV2 has following date structure:
#Temporal(TemporalType.DATE)
#Column(name = "EFFECTIVE_DATE")
#JsonProperty("EFFECTIVE_DATE")
private Date effectiveDate;
When spring boot starts I get the following exception:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'corporateActionV2Service' defined in file [D:\company\content_contribution_platform\application\target\classes\com\mubasher\ccp\services\CorporateActionV2Service.class]: Unsatisfied dependency expressed through constructor parameter 1: Error creating bean with name 'corporateActionV2Repository' defined in com.mubasher.ccp.repositories.ms.history.CorporateActionV2Repository defined in #EnableJpaRepositories declared on MSHistoryConfig: Could not create query for public abstract java.util.List com.mubasher.ccp.repositories.ms.history.CorporateActionV2Repository.getDuplicateActions(); Reason: Validation failed for query for method public abstract java.util.List com.mubasher.ccp.repositories.ms.history.CorporateActionV2Repository.getDuplicateActions()
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:793)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:242)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1188)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:561)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:961)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:915)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291)
at com.mubasher.ccp.Application.main(Application.java:29)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'corporateActionV2Repository' defined in com.mubasher.ccp.repositories.ms.history.CorporateActionV2Repository defined in #EnableJpaRepositories declared on MSHistoryConfig: Could not create query for public abstract java.util.List com.mubasher.ccp.repositories.ms.history.CorporateActionV2Repository.getDuplicateActions(); Reason: Validation failed for query for method public abstract java.util.List com.mubasher.ccp.repositories.ms.history.CorporateActionV2Repository.getDuplicateActions()
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1751)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1405)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1325)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:880)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:784)
... 24 common frames omitted
Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.mubasher.ccp.repositories.ms.history.CorporateActionV2Repository.getDuplicateActions(); Reason: Validation failed for query for method public abstract java.util.List com.mubasher.ccp.repositories.ms.history.CorporateActionV2Repository.getDuplicateActions()
at org.springframework.data.repository.query.QueryCreationException.create(QueryCreationException.java:101)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:115)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.mapMethodsToQuery(QueryExecutorMethodInterceptor.java:99)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$new$0(QueryExecutorMethodInterceptor.java:88)
at java.base/java.util.Optional.map(Optional.java:260)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.<init>(QueryExecutorMethodInterceptor.java:88)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:357)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:279)
at org.springframework.data.util.Lazy.getNullable(Lazy.java:229)
at org.springframework.data.util.Lazy.get(Lazy.java:113)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:285)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:132)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1797)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1747)
... 35 common frames omitted
Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.mubasher.ccp.repositories.ms.history.CorporateActionV2Repository.getDuplicateActions()
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:100)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:70)
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:55)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:170)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:252)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:95)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:111)
... 47 common frames omitted
Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: Parameter 1 of function to_date() has type STRING, but argument is of type java.util.Date
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:141)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:175)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:182)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:761)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:663)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:127)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:360)
at jdk.proxy3/jdk.proxy3.$Proxy139.createQuery(Unknown Source)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:94)
... 53 common frames omitted
Caused by: org.hibernate.QueryException: Parameter 1 of function to_date() has type STRING, but argument is of type java.util.Date
at org.hibernate.query.sqm.produce.function.ArgumentTypesValidator.throwError(ArgumentTypesValidator.java:214)
at org.hibernate.query.sqm.produce.function.ArgumentTypesValidator.checkType(ArgumentTypesValidator.java:169)
at org.hibernate.query.sqm.produce.function.ArgumentTypesValidator.validate(ArgumentTypesValidator.java:74)
at org.hibernate.query.sqm.function.AbstractSqmFunctionDescriptor.generateSqmExpression(AbstractSqmFunctionDescriptor.java:104)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitGenericFunction(SemanticQueryBuilder.java:3664)
at org.hibernate.grammars.hql.HqlParser$GenericFunctionContext.accept(HqlParser.java:10209)
at org.antlr.v4.runtime.tree.AbstractParseTreeVisitor.visitChildren(AbstractParseTreeVisitor.java:46)
at org.hibernate.grammars.hql.HqlParserBaseVisitor.visitFunction(HqlParserBaseVisitor.java:1112)
at org.hibernate.grammars.hql.HqlParser$FunctionContext.accept(HqlParser.java:9977)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitFunctionExpression(SemanticQueryBuilder.java:1432)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitFunctionExpression(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$FunctionExpressionContext.accept(HqlParser.java:6849)
at org.antlr.v4.runtime.tree.AbstractParseTreeVisitor.visitChildren(AbstractParseTreeVisitor.java:46)
at org.hibernate.grammars.hql.HqlParserBaseVisitor.visitBarePrimaryExpression(HqlParserBaseVisitor.java:671)
at org.hibernate.grammars.hql.HqlParser$BarePrimaryExpressionContext.accept(HqlParser.java:6437)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitAdditionExpression(SemanticQueryBuilder.java:2613)
at org.hibernate.grammars.hql.HqlParser$AdditionExpressionContext.accept(HqlParser.java:6395)
at org.antlr.v4.runtime.tree.AbstractParseTreeVisitor.visitChildren(AbstractParseTreeVisitor.java:46)
at org.hibernate.grammars.hql.HqlParserBaseVisitor.visitExpressionOrPredicate(HqlParserBaseVisitor.java:811)
at org.hibernate.grammars.hql.HqlParser$ExpressionOrPredicateContext.accept(HqlParser.java:7186)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitGenericFunctionArguments(SemanticQueryBuilder.java:3781)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitGenericFunctionArguments(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$GenericFunctionArgumentsContext.accept(HqlParser.java:10559)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitGenericFunction(SemanticQueryBuilder.java:3563)
at org.hibernate.grammars.hql.HqlParser$GenericFunctionContext.accept(HqlParser.java:10209)
at org.antlr.v4.runtime.tree.AbstractParseTreeVisitor.visitChildren(AbstractParseTreeVisitor.java:46)
at org.hibernate.grammars.hql.HqlParserBaseVisitor.visitFunction(HqlParserBaseVisitor.java:1112)
at org.hibernate.grammars.hql.HqlParser$FunctionContext.accept(HqlParser.java:9977)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitFunctionExpression(SemanticQueryBuilder.java:1432)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitFunctionExpression(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$FunctionExpressionContext.accept(HqlParser.java:6849)
at org.antlr.v4.runtime.tree.AbstractParseTreeVisitor.visitChildren(AbstractParseTreeVisitor.java:46)
at org.hibernate.grammars.hql.HqlParserBaseVisitor.visitBarePrimaryExpression(HqlParserBaseVisitor.java:671)
at org.hibernate.grammars.hql.HqlParser$BarePrimaryExpressionContext.accept(HqlParser.java:6437)
at org.antlr.v4.runtime.tree.AbstractParseTreeVisitor.visitChildren(AbstractParseTreeVisitor.java:46)
at org.hibernate.grammars.hql.HqlParserBaseVisitor.visitExpressionOrPredicate(HqlParserBaseVisitor.java:811)
at org.hibernate.grammars.hql.HqlParser$ExpressionOrPredicateContext.accept(HqlParser.java:7186)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitExpressions(SemanticQueryBuilder.java:2736)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitTupleExpression(SemanticQueryBuilder.java:2724)
at org.hibernate.grammars.hql.HqlParser$TupleExpressionContext.accept(HqlParser.java:6465)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitInPredicate(SemanticQueryBuilder.java:2282)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitInPredicate(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$InPredicateContext.accept(HqlParser.java:5466)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitWhereClause(SemanticQueryBuilder.java:1949)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitWhereClause(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$WhereClauseContext.accept(HqlParser.java:5290)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuery(SemanticQueryBuilder.java:857)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuerySpecExpression(SemanticQueryBuilder.java:629)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuerySpecExpression(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$QuerySpecExpressionContext.accept(HqlParser.java:1218)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSimpleQueryGroup(SemanticQueryBuilder.java:623)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSimpleQueryGroup(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$SimpleQueryGroupContext.accept(HqlParser.java:1131)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSelectStatement(SemanticQueryBuilder.java:399)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitStatement(SemanticQueryBuilder.java:358)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.buildSemanticModel(SemanticQueryBuilder.java:285)
at org.hibernate.query.hql.internal.StandardHqlTranslator.translate(StandardHqlTranslator.java:81)
at org.hibernate.internal.AbstractSharedSessionContract.lambda$createQuery$2(AbstractSharedSessionContract.java:748)
at org.hibernate.query.internal.QueryInterpretationCacheStandardImpl.createHqlInterpretation(QueryInterpretationCacheStandardImpl.java:141)
at org.hibernate.query.internal.QueryInterpretationCacheStandardImpl.resolveHqlInterpretation(QueryInterpretationCacheStandardImpl.java:128)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:745)
... 62 common frames omitted
What am I missing from hibernate-5 to hibernate-6? The code was working fine in older version and from docs there is not much difference between hibernate 5 & 6.
As correctly answered by Octavia Adler, it makes no sense to pass a date to the to_date() function.
As of Hibernate 6, the argument types of HQL functions are now typechecked, and so Hibernate will pick up errors of this nature and report them with a sensible error message, in this case:
org.hibernate.QueryException: Parameter 1 of function to_date() has type STRING, but argument is of type java.util.Date
Perhaps you missed this message because Spring appears to be wrapping the helpful exception from Hibernate in not just one or two but four different useless exceptions that fail to preserve the error message of the root cause.
You should complain to the Spring developers about this, because this is just a terrible practice in terms of library design, IMO.
Your error says: Parameter 1 of function to_date() has type STRING, but argument is of type java.util.Date.
In your query, is written: TO_CHAR(TO_DATE(ca.effectiveDate) - 5,'IYYY').
So based on this, I guess your ca.effectiveDate is already of type Date and it needs a string.
You should write something like this: TO_CHAR(ca.effectiveDate - 5,'IYYY')
We had a similar error since upgrading to SpringBoot 3. However, it affects trunc and only occurs with oracle. It works wonderfully against an H2 database. Our error
Looks like a bug. The assumption by beikov (Hibernate team member):
It seems that the trunc function has multiple overloads but Hibernate 6 only supports the numeric variant right now
I have already created the following issue on Hibernate tracker.
Should be a similar problem here.

Issues with initializing service class that has dependency on running application on startup (play 2.4 / scala)

I am currently digging into using Quartz in our play 2.4 application.
Initially, I tried initializing everything through Global object, and everything worked perfectly.
Now, I an trying to move away from Global utilize modules infrastructure.
Here is what I have until now.
JobSchedulingService
#Singleton
class JobSchedulingService #Inject()(lifecycle: ApplicationLifecycle) extends ClassLogger{
lazy val schedulerFactory = current.injector.instanceOf[StdSchedulerFactory]
lazy val scheduler = schedulerFactory.getScheduler
/**
* Let's make sure that scheduler shuts down properly
*/
lifecycle.addStopHook{ () =>
Future.successful{
if (scheduler.isStarted) {
scheduler.shutdown(true)
}
}
}
protected def init() : Unit = {
logger.info("Initializing scheduler...")
scheduler.start()
}
init()
}
SchedulerModule - here for initialization of the service above.
class SchedulerModule extends AbstractModule{
override def configure(): Unit = {
bind(classOf[JobSchedulingService]).asEagerSingleton
}
}
And in my application.conf I added:
play.modules.enabled += "scheduling.modules.SchedulerModule"
It looks pretty strait forward. However, when the app starts I am getting an exception:
2016-03-23 00:07:42,173 INFO s.JobSchedulingService - Initializing
scheduler... 2016-03-23 00:07:42,213 ERROR application -
! #6pfp72mh6 - Internal server error, for (GET) [/] ->
play.api.UnexpectedException: Unexpected exception[CreationException:
Unable to create injector, see the following errors:
1) Error injecting constructor, java.lang.RuntimeException: There is
no started application at
scheduling.JobSchedulingService.(JobSchedulingService.scala:15)
at
scheduling.modules.SchedulerModule.configure(SchedulerModule.scala:11)
(via modules: com.google.inject.util.Modules$OverrideModule ->
scheduling.modules.SchedulerModule) while locating
scheduling.JobSchedulingService
...
The thing is, in our app, the scheduler is based of off persistence job storage and should restart when the application restarts. Again, when I did it through Global, it worked perfectly.
How do I get around this problem? What is the correct way to initialize an instance on startup?
Thanks,
You should probably be using the dependency injection for everything. Inject the scheduler like..
class JobSchedulingService #Inject()(lifecycle: ApplicationLifecycle, schedulerFactory: StdSchedulerFactory) extends ClassLogger{
lazy val scheduler = schedulerFactory.getScheduler
Hmmm...
I think I just resolved it.
It seems like the problem was not the actual initialization of a class, but this line:
lazy val schedulerFactory = current.injector.instanceOf[StdSchedulerFactory]
once I changed it to:
lazy val schedulerFactory = new StdSchedulerFactory
it started working.
May that will help somebody

Spark: java.io.NotSerializableException: org.apache.avro.Schema$RecordSchema

I am creating avro RDD with following code.
def convert2Avro(data : String ,schema : Schema) : AvroKey[GenericRecord] = {
var wrapper = new AvroKey[GenericRecord]()
var record = new GenericData.Record(schema)
record.put("empname","John")
wrapper.datum(record)
return wrapper
}
and creating avro RDD as follows.
var avroRDD = fieldsRDD.map(x =>(convert2Avro(x, schema)))
while executing, I am getting following exception in above line
Exception in thread "main" org.apache.spark.SparkException: Task not serializable
at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:166)
at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:158)
at org.apache.spark.SparkContext.clean(SparkContext.scala:1242)
at org.apache.spark.rdd.RDD.map(RDD.scala:270)
at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:331)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:75)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.io.NotSerializableException: org.apache.avro.Schema$RecordSchema
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1183)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1547)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1508)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431)
any pointer?
Schema.ReocrdSchema class has not implemented serializable. So it could not transferred over the network. We can convert the schema to string and pass to method and inside the method reconstruct the schema object.
var schemaString = schema.toString
var avroRDD = fieldsRDD.map(x =>(convert2Avro(x, schemaString)))
Inside the method reconstruct the schema:
def convert2Avro(data : String ,schemaString : String) : AvroKey[GenericRecord] = {
var schema = parser.parse(schemaString)
var wrapper = new AvroKey[GenericRecord]()
var record = new GenericData.Record(schema)
record.put("empname","John")
wrapper.datum(record)
return wrapper
}
Another alternative (from http://aseigneurin.github.io/2016/03/04/kafka-spark-avro-producing-and-consuming-avro-messages.html) is to use static initialization.
as they explain on the link
we are using a static initialization block. An instance of the
recordInjection object will be created per JVM, i.e. we will have one
instance per Spark worker
And since it's created fresh for each worker, there is no serialization needed.
I prefer the static initializer, as I would worry that toString() might not contain all the information needed to construct the object (it seems to work well in this case, but serialization is not toString()'s advertised purpose). However, the disadvantage of using static is that it's not really a correct use of static (see, for example, Java: when to use static methods)
So, whichever you prefer - since both seem to work fine, then it's probably more a matter of your preferred style.
Update
Of course, depending on your program, the most elegant solution might be to avoid the problem all together, by containing all your avro code in the worker i.e. do all the Avro processing you need to do, like writing to the Kafka topic or whatever, in "convert2Avro". Then there is no need to return these objects back into an RDD. It really depends what you are wanting the RDD for.

Accessing dynamic databases via spring-data-mongodb

I am trying to access data from different databases based on a runtime variable. For this purpose, I have a custom implementation of MongoOperations. My implementation is same as MongoTemplate except my getDb() method looks like below:
public DB getDb() {
return mongoDbFactory.getDb(PropertyManager.getCurrentTenant().getCode());
}
While reading data in a transaction, I am getting below error:
[TransactionSynchronizationUtils] - TransactionSynchronization.beforeCompletion threw exception
java.lang.IllegalStateException: No value for key [Mongo: localhost/127.0.0.1:27017] bound to thread
It appears harmless as this exception is only logged:
public static void triggerBeforeCompletion() {
for (TransactionSynchronization synchronization : TransactionSynchronizationManager.getSynchronizations()) {
try {
synchronization.beforeCompletion();
}
catch (Throwable tsex) {
logger.error("TransactionSynchronization.beforeCompletion threw exception", tsex);
}
}
}
But I am having a hard time figuring out why this is happening. Any clues?
Versions:
spring-data-mongodb: 1.2.3.RELEASE
spring-tx: 4.0.5.RELEASE
There was a bug raised for similar issue which was fixed in 1.1 GA release.
It worked by extending
SimpleMongoDbFactory: returning custom DB in DB getDb(String dbName).
MongoTemplate: Supplying above factory.

RESTEasy cannot call my annotated method on a scala class

Trying to implement a JAX-RS resource in Scala. My Java version of this has the following type signature:
#GET
#Path(value="echoold")
#Produces("application/json")
public Map<String,Object> get(
#QueryParam("param") String param,
#QueryParam("asOf") #DefaultValue(NOW) DateWrapper asOf,
#QueryParam("httpError") #DefaultValue("200") int httpError,
#QueryParam("httpErrorMessage") #DefaultValue("") String httpErrorMessage,
#QueryParam("fail") #DefaultValue("false") boolean fail) {
The Scala version is thus:
#GET
#Path(value="echo")
#Produces(Array("application/json"))
def get() = {
#QueryParam("param") param:String,
#QueryParam("asOf") #DefaultValue(NOW) asOf:DateWrapper,
#QueryParam("httpError") #DefaultValue("200") httpError:java.lang.Integer,
#QueryParam("httpErrorMessage") #DefaultValue("") httpErrorMessage:String,
#QueryParam("fail") #DefaultValue("false") fail:java.lang.Boolean):java.util.Map[String,Object] = {
When I start up my application, I get this strange error from RESTEasy (which I've formatted for readability):
org.jboss.resteasy.spi.InternalServerErrorException:
Bad arguments passed to
public java.util.Map opower.api.endpoint.echo.Echo.get(java.lang.String,
opower.api.support.DateWrapper,
java.lang.Integer,
java.lang.String,
java.lang.Boolean)
( java.lang.String someValue,
opower.api.support.DateWrapper opower.api.support.DateWrapper#28a34522,
java.lang.Integer 400,
java.lang.String This is the message,
java.lang.Boolean false )
The underlying exception is:
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:140)
Now, this class is configured via Spring, so it could be some crazy proxy class and it's getting messed up, but has anyone else seen something like this?
(If you don't know what RESTEasy/JAX-RS is doing, basically the container (RESTEasy) finds methods on classes that have those annotations on them, and then calls them when certain URL endpoints are hit)
I had the same with Spring/Scala and #Transactional method annotation.
needed to change proxy-target-class in
<tx:annotation-driven transaction-manager="txManager"
mode="proxy" proxy-target-class="true"/>
Default value for proxy-target-class is false. It requires cglib in classpath.
I guess mode="acpectj" might also work (didn't try)