I'm having a hard time configuring a ModelMapper so that it can convert a LocalDateTime property into a long.
Here is my source class:
public class Source {
private LocalDateTime time;
public LocalDateTime getTime() {
return time;
}
public void setTime(LocalDateTime time) {
this.time = time;
}
}
my destination class:
public class Destination {
private long time;
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
}
I configure my ModelMapper as follows:
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration()
.setMatchingStrategy(MatchingStrategies.STRICT);
mapper.typeMap(Source.class, Destination.class)
.addMappings(map -> {
map.map(src -> toMillis(src.getTime()), Destination::setTime);
});
...
private static long toMillis(LocalDateTime dt) {
if (dt == null) {
return 0;
}
ZonedDateTime zdt = ZonedDateTime.of(dt, ZoneId.systemDefault());
return zdt.toInstant().toEpochMilli();
}
And use it as follows:
Source src = new Source();
src.setTime(LocalDateTime.now());
Destination dst = mapper.map(src, Destination.class);
But I'm getting the exception bellow:
Exception in thread "main" org.modelmapper.MappingException: ModelMapper
mapping errors:
1) Converter org.modelmapper.internal.converter.NumberConverter#72967906
failed to convert java.time.LocalDateTime to long.
1 error
at
org.modelmapper.internal.Errors.throwMappingExceptionIfErrorsExist(Errors.java:380)
at
org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:80)
at org.modelmapper.ModelMapper.mapInternal(ModelMapper.java:573)
at org.modelmapper.ModelMapper.map(ModelMapper.java:406)
at org.tastefuljava.test19.Main.main(Main.java:21)
Caused by: org.modelmapper.MappingException: ModelMapper mapping errors:
1) Error mapping 2023-01-09T12:47:56.793910 to java.lang.Long
1 error
at org.modelmapper.internal.Errors.toMappingException(Errors.java:258)
at
org.modelmapper.internal.converter.NumberConverter.numberFor(NumberConverter.java:181)
at
org.modelmapper.internal.converter.NumberConverter.convert(NumberConverter.java:75)
at
org.modelmapper.internal.converter.NumberConverter.convert(NumberConverter.java:57)
at
org.modelmapper.internal.MappingEngineImpl.convert(MappingEngineImpl.java:306)
at
org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:109)
at
org.modelmapper.internal.MappingEngineImpl.setDestinationValue(MappingEngineImpl.java:245)
at
org.modelmapper.internal.MappingEngineImpl.propertyMap(MappingEngineImpl.java:187)
at
org.modelmapper.internal.MappingEngineImpl.typeMap(MappingEngineImpl.java:151)
at
org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:105)
at
org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:71)
... 3 more
Caused by: java.lang.NumberFormatException: For input string:
"2023-01-09T12:47:56.793910"
at
java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Long.parseLong(Long.java:711)
at java.base/java.lang.Long.valueOf(Long.java:1159)
at
org.modelmapper.internal.converter.NumberConverter.numberFor(NumberConverter.java:171)
... 12 more
Command execution failed.
org.apache.commons.exec.ExecuteException: Process exited with an error:
1 (Exit value: 1)
at
org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:404)
at
org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:166)
at
org.codehaus.mojo.exec.ExecMojo.executeCommandLine(ExecMojo.java:982)
at
org.codehaus.mojo.exec.ExecMojo.executeCommandLine(ExecMojo.java:929)
at org.codehaus.mojo.exec.ExecMojo.execute(ExecMojo.java:457)
at
org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
at
org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
at
org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at
org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at
org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
at
org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
at
org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
at
org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
at
java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at
org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at
org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at
org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at
org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Could anyone help me fix this?
Thanks in advance
That's an issue with ModelMapper, where it is not able to bind complete lambda for mapping and just mapping src.getTime() and that's why you are getting error so either you can have time field as long in your Source class or can move toMillis method inside Source class something like below -
public class Source {
private LocalDateTime time;
public LocalDateTime getTime() {
return time;
}
public void setTime(LocalDateTime time) {
this.time = time;
}
public long toMillis() {
if (time == null) {
return 0;
}
ZonedDateTime zdt = ZonedDateTime.of(time, ZoneId.systemDefault());
return zdt.toInstant().toEpochMilli();
}
}
and then can change mapping code like below -
mapper.typeMap(Source.class, Destination.class)
.addMappings(map -> map.map(Source::toMillis, Destination::setTime));
Related
I've done a program where I have to retrieve the data from a table in MS SQL. I'm using Hibernate where AbtDebtbyCAN is an Entity class. The connection so far is fine but the only problem I'm facing is printing out data from MS SQL using Annotation Mapping. Debt is the name of the table(the name of the table is in lower case) which is to be mapped with. Below here is the result I want to print it out using Hibernate. Can anybody help me on how to achieve the fetching of data?
debt
id can bdrl_debt excess_ta_debt posting_ref debt_settlement_id debt_settlement_at debt_business_date
11425 1099112400000003 0 200 501728 137 2020-10-13 10:51:50.000 2020-10-13
AbtDebtbyCAN
#Data
#Entity
#Table(name = "debt")
public class AbtDebtbbyCAN implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int debt_id;
#Column(name = "can")
private int debt_can;
#Column(name = "bdrl_debt")
private int bdrl_debt;
#Column(name = "excess_ta_debt")
private int excess_ta_debt;
#Column(name = "posting_ref")
private int posting_ref;
#Column(name = "debt_settlement_id")
private int debt_settlement_id;
#Column(name = "debt_settlement_at")
private DateTime debt_settlement_at;
#Column(name = "debt_business_date")
private Date debt_business_date;
}
AbtCANMapperTest
public class AbtCANMapperTest {
public static void main(String args[]) {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
List abtdebt = session.createQuery("FROM AbtDebtbbyCAN WHERE debt_can=1099112400000003").getResultList();
for (Iterator iterator = abtdebt.iterator(); iterator.hasNext(); ) {
AbtDebtbbyCAN abtcan = (AbtDebtbbyCAN) iterator.next();
System.out.print("debt id: " + abtcan.getDebt_id());
System.out.print("debt can: " + abtcan.getDebt_can());
System.out.print("bdrl debt: " + abtcan.getBdrl_debt());
System.out.print("excess debt: " + abtcan.getExcess_ta_debt());
System.out.print("posting ref: " + abtcan.getPosting_ref());
System.out.print("debt settlement id: " + abtcan.getDebt_settlement_id());
System.out.print("debt settlement at: " + abtcan.getDebt_settlement_at());
System.out.println("debt business date: " + abtcan.getDebt_business_date());
}
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
Error StackTrace
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.type.SerializationException: could not deserialize
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1542)
at org.hibernate.query.Query.getResultList(Query.java:165)
at AbtMainTestControl.AbtTestObj.AbtCANMapperTest.main(AbtCANMapperTest.java:36)
Caused by: org.hibernate.type.SerializationException: could not deserialize
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:243)
at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:287)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:138)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:113)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:29)
at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:60)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:243)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:329)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:3088)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1907)
at org.hibernate.loader.Loader.hydrateEntityState(Loader.java:1835)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1808)
at org.hibernate.loader.Loader.getRow(Loader.java:1660)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:745)
at org.hibernate.loader.Loader.getRowsFromResultSet(Loader.java:1044)
at org.hibernate.loader.Loader.processResultSet(Loader.java:995)
at org.hibernate.loader.Loader.doQuery(Loader.java:964)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:350)
at org.hibernate.loader.Loader.doList(Loader.java:2887)
at org.hibernate.loader.Loader.doList(Loader.java:2869)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2701)
at org.hibernate.loader.Loader.list(Loader.java:2696)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:506)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:400)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:219)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1415)
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1565)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1533)
... 2 more
Caused by: java.io.StreamCorruptedException: invalid stream header: 0000AC53
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:899)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:357)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:309)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:299)
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:218)
... 32 more
Caused by: org.hibernate.type.SerializationException: could not deserialize
> Task :AbtCANMapperTest.main() FAILED
Caused by: java.io.StreamCorruptedException: invalid stream header: 0000AC53
Execution failed for task ':AbtCANMapperTest.main()'.
> Process 'command 'C:/Program Files/Java/jdk1.8.0_241/bin/java.exe'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
Not sure what types you are exactly using here, but at least DateTime is not a standard type that is supported by Hibernate. If Hibernate does not know about a type, it tries to flush the value in its serialized form as blob/byte[]. If you would use java.sql.Timestamp, java.util.Calendar or any other type that is supported by Hibernate out of the box, this should work properly.
when spring boot first startup, jooq works well.
but if i make change to code and after spring boot context refreshed,
then i stucked in trouble with class cast exception.
the problem is cast exception on same class.
my boot conf is :
#Autowired
private DataSource dataSource;
public ExecuteListener exceptionTransformer() {
return new DefaultExecuteListener() {
private static final long serialVersionUID = 1L;
#Override
public void exception(ExecuteContext context) {
SQLDialect dialect = context.configuration().dialect();
SQLExceptionTranslator translator = (dialect != null)
? new SQLErrorCodeSQLExceptionTranslator(dialect.name())
: new SQLStateSQLExceptionTranslator();
context.exception(
translator.translate("jOOQ", context.sql(), context.sqlException()));
}
};
}
#Primary
#Bean
public DefaultDSLContext dsl() {
return new DefaultDSLContext(configuration());
}
public DataSourceConnectionProvider connectionProvider() {
return new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(dataSource));
}
public DefaultConfiguration configuration() {
DefaultConfiguration configuration = new DefaultConfiguration();
configuration.set(connectionProvider());
configuration.set(new DefaultExecuteListenerProvider(exceptionTransformer()));
configuration.set(SQLDialect.MYSQL);
// #formatter:off
configuration.set(
new Settings()
.withExecuteLogging(true)
.withRenderFormatted(true)
);
// #formatter:on
configuration.set(SfmRecordMapperProviderFactory.newInstance().ignorePropertyNotFound().newProvider());
return configuration;
}
query code is :
User user = dsl.select()
.from(USER)
.where(USER.USER_ID.eq(id)).fetchOneInto(User.class);
admin.domain.User is:
#Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String userId;
#JsonIgnore
private String pswd;
private String name;
private String useYn;
private Timestamp registDatetime;
private Timestamp updateDatetime;
}
stack trace is :
java.lang.ClassCastException: admin.domain.User cannot be cast to admin.domain.User
at admin.dao.UserDao.getUserByIdWithRoles(UserDao.java:123)
at admin.dao.UserDao$$FastClassBySpringCGLIB$$f7b71f39.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:747)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:89)
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)
what is my fault?
Do you have spring boot automatic restart enabled?
This look likes it, you could try:
to run without the devtools (https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html#using-boot-devtools-restart-disable)
add the correct path to your live reload (
https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html#using-boot-devtools-restart-additional-paths and https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html#using-boot-devtools-customizing-classload )
:)
I'm implementing an object that represents a graph to be stored in a MongoDb. Here's the class definition:
#Document(collection = "mygraph")
public class MyGraph {
#Id
#JsonSerialize(using = ToStringSerializer.class)
public String id;
public Map<Instance, Set<Instance>> graph;
public String timestamp;
/**
* Add the default constructor
*/
public MyGraph() {
this.id = new ObjectId().toHexString();
this.graph = new LinkedHashMap<>();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
this.timestamp = dateFormat.format(new Date());
}
/**
*
* #param instances
*/
public MyGraph(Set<Instance> instances) {
this.id = new ObjectId().toHexString();
this.graph = new LinkedHashMap<>();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
this.timestamp = dateFormat.format(new Date());
/* Initialize the graph */
for (Instance instance : instances) {
this.graph.put(instance, new HashSet<>());
}
}
// get and set method are below
}
However I'm getting the following error:
Time elapsed: 0.03 sec <<< FAILURE!
org.springframework.data.mapping.model.MappingException: Cannot use a complex object as a key value.
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeMapInternal(MappingMongoConverter.java:669)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.createMap(MappingMongoConverter.java:585)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writePropertyInternal(MappingMongoConverter.java:471)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$3.doWithPersistentProperty(MappingMongoConverter.java:430)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$3.doWithPersistentProperty(MappingMongoConverter.java:418)
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:312)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:418)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:392)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.write(MappingMongoConverter.java:356)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.write(MappingMongoConverter.java:79)
at org.springframework.data.mongodb.core.MongoTemplate.toDbObject(MongoTemplate.java:853)
at org.springframework.data.mongodb.core.MongoTemplate.doSave(MongoTemplate.java:1014)
at org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:963)
at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.save(SimpleMongoRepository.java:80)
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.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:503)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:488)
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.$Proxy197.save(Unknown Source)
at models.CloudGraphTest.testSaveCloudGraph(CloudGraphTest.java:79)
How can I change my MappingMongoConverter to accomodate for that?
There's an open Improvement in Spring: Don't require Converters for Complex classes that are used as Ids.
Unfortunately, currently Spring team decided not to support it.
decided not to support it at all
EDIT
There's an open related issue Allow using complex types as Map keys that may include a fix later
I was using JPA AttributeConverter with spring boot 1.2.1 RELEASE and it worked fine. But I get the following error after upgrading to spring boot 1.3.0.RELEASE
Caused by: javax.persistence.PersistenceException: Error attempting to apply AttributeConverter
at org.hibernate.type.descriptor.converter.AttributeConverterSqlTypeDescriptorAdapter$1.bind(AttributeConverterSqlTypeDescriptorAdapter.java:103)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:286)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:281)
at org.hibernate.type.AbstractSingleColumnStandardBasicType.nullSafeSet(AbstractSingleColumnStandardBasicType.java:56)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2843)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3248)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3183)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3525)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:159)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:465)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:351)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:77)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
... 81 more
Caused by: java.lang.NullPointerException
at rafito.spring.boot.domain.TimestampPersistenceConverter.convertToDatabaseColumn(TimestampPersistenceConverter.java:16)
at rafito.spring.boot.domain.TimestampPersistenceConverter.convertToDatabaseColumn(TimestampPersistenceConverter.java:10)
at org.hibernate.type.descriptor.converter.AttributeConverterSqlTypeDescriptorAdapter$1.bind(AttributeConverterSqlTypeDescriptorAdapter.java:97)
I am not setting serviceBeginTime and serviceEndTime in my POST JSON currently. But this wasn't giving me a null pointer before I upgraded spring boot version.
Converter class
#Converter
public class TimestampPersistenceConverter implements AttributeConverter<Long, Timestamp> {
#Override
public Timestamp convertToDatabaseColumn(Long aLong) {
return new Timestamp(aLong);
}
#Override
public Long convertToEntityAttribute(Timestamp timestamp) {
return timestamp.getTime();
}
}
Entity
#Column(name = "service_begin_time")
#Convert(converter = TimestampPersistenceConverter.class)
Long serviceBeginTime;
#Column(name = "service_end_time")
#Convert(converter = TimestampPersistenceConverter.class)
Long serviceEndTime;
Database fields
service_begin_time timestamp without time zone,
service_end_time timestamp without time zone,
Added a null check as that was the easiest.
#Override
public Timestamp convertToDatabaseColumn(Long aLong) {
if (aLong == null)
return null;
return new Timestamp(aLong);
}
I'm trying to get a JSON object displayed via an API, but I get a error message along with it.
Here is the method that I've written:
public MarketDataListLevel1 getMarketDataTicker() {
try {
MarketDataListLevel1 md = CS.getMarketDataTicker();
log.info(md.toString());
return md;
}
catch ( Exception e) {
e.printStackTrace();
return null;
}
}
Where CS is an object that processes the JSON data from a URL..
For some reason, when I call that method, I'm getting the precise output that I want, but I also get these additional error messages that follow it, and I'm unsure why. Any help would be appreciated.
14:52:55.265 [default] [main] ERROR si.mazi.rescu.JSONUtils - Error unmarshalling from
json: {"Bid":{"Price":183.25,"Size":0.0,"ExchangeID":"SMART","timeStamp":0},"Ask":{"Price":185.0,"Size":0.0,"ExchangeID":"SMART","timeStamp":0},"Last":{"Price":182.44,"Size":4.0,"ExchangeID":"SMART","timeStamp":0}}
java.lang.RuntimeException: Problem getting JSON object
at (Skipped all these logs)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.xeiam.xchange.cs.dto.MarketData[] out of START_OBJECT token
at [Source: java.io.StringReader#5069bb01; line: 1, column: 2]
This is the format of the data what I want returned:
{"Bid":{"Price":204.08,"Size":1.0,"ExchangeID":"SMART","timeStamp":0},
"Ask":{"Price":203.2,"Size":0.0,"ExchangeID":"SMART","timeStamp":0},
"Last":{"Price":204.64,"Size":2.0,"ExchangeID":"SMART","timeStamp":0}}
And it seems to be fulfilling that.
MarketDataLevel1 is defined as:
public class MarketDataListLevel1 {
public MarketData[] MarketDataListLast;
public MarketData[] MarketDataListBid;
public MarketData[] MarketDataListAsk;
public MarketDataListLevel1(#JsonProperty("Bid") MarketData[] MarketDataListBid,#JsonProperty("Ask") MarketData[] MarketDataListAsk,#JsonProperty("Last") MarketData[] MarketDataListLast) {
this.MarketDataListBid = MarketDataListBid;
this.MarketDataListAsk = MarketDataListAsk;
this.MarketDataListLast = MarketDataListLast;
}
And MarketData as
public class MarketData {
public BigDecimal Price;
public BigDecimal Size;
public String ExchangeID;
public long timeStamp;
public MarketData(
#JsonProperty("Price") BigDecimal Price,
#JsonProperty("Size") BigDecimal Size,
#JsonProperty("ExchangeID") String ExchangeID,
#JsonProperty("timeStamp") long timeStamp) {
this.Price = Price;
this.Size = Size;
this.ExchangeID = ExchangeID;
this.timeStamp = timeStamp;
}
}