java data jpa,使用Java 8 LocalDateTime的Spring Data JPA

I have been working with Spring Data JPA and MYSQL last couple of months and it has been a quite successful and smooth experience. In there i am using java 8 LocalDateTime to store the date time fields and the JPA automatically maps those fields in to mysql tinyblob columns.

Recently i got a requirement to add some data through a script to the system. In Order to fill the date time columns, i have created MYSQL TIMESTAMP variables and inserted into tinyblob columns. However system started complaining SerializationException and the root cause for that is this converted datetime columns.

then i had a look at the date time columns inserted through the application as below

select CAST(drop_off_time AS CHAR(10000) CHARACTER SET utf8) From job

67d93b9714fbc36c4a82b677cf4b09ff.png

it looks like that when you insert through the application, it inserted as some kind of java serialization. However through a mysql script we can not replicate that functionality.

Now i have two options.

1) I need to find a way to write a mysql script to generate the Date time columns similar to the application.

2) I need to change the Spring data JPA mapping from tinyblob to an another data type which mysql scripts can support

Appreciate your help

Thanks,

Keth

EDIT

After following the answers and comments provided below, i was able to find a simple solution

if you use Hibernate 5.0+, you can drop in

org.hibernate

hibernate-java8

${hibernate.version}

Then the system starts mapping the java 8 LocalDateTime prperties in to mysql DATETIME columns

解决方案

According to JPA 2.1 LocalDateTime isn't suppoorted oficially (probably in short time JPA 2.,2 will be official). Hibernate 5 support as 'early release'

Portable and supported since JPA 2.0 is javax.persistence.AttributeConverter, works very well on all JPA providers (and makes nothing bad on Hibernate 5)

@Converter(autoApply = true)

public class LocalDateAttributeConverter implements AttributeConverter {

@Override

public Date convertToDatabaseColumn(LocalDate locDate) {

return (locDate == null ? null : Date.valueOf(locDate));

}

@Override

public LocalDate convertToEntityAttribute(Date sqlDate) {

return (sqlDate == null ? null : sqlDate.toLocalDate());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值