java - hibernate 时间类型转换,date 属性的时间字段取出来后变样了

查看:273
本文介绍了java - hibernate 时间类型转换,date 属性的时间字段取出来后变样了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

这个是字段属性

@Column(name = "create_time",insertable = false,updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date create_time;

保存在mysql的时候数据是正确的,
create_time
2016-08-30 09:27:30
2016-08-30 09:31:32

但是取出来的时候变成了

"create_time": "2016-08-30T01:31:32.000+0000",

这种时间,怎么才能做成数据库那样的时间返回格式呢
程序是直接return 这个对象后 返回 json 的
自己查询过一些答案,都是取出来自己去格式化的,可是我这里是直接返回对象json解析,对象的属性是 date 类型,格式化后转换成 string 后没办法 set 了

这个程序里面我看之前的人好像写了一个自定义类型的 string-binary (对应数据库存 varbinary)

@Column(name = "content",nullable = false)
@Type(type = "string-binary")
private String content;

这个时间是不是也得需要这样,自己自定义一个类型去弄?

还有,我想以后数据库保存时间字段都保存成时间戳该怎么注解字段的默认值呢

我是从PHP转到Java来的,不怎么懂
公司的Java跑了,唉,赶鸭子上架

解决方案

最后自己找到了解决方案:
需要自己增加一个自定义类型
自定义类 LocalDateTimeType

package com.meclass.hibernate;

public class LocalDateTimeType extends org.hibernate.type.LocalDateTimeType
{
    
    public static final LocalDateTimeType INSTANCE = new LocalDateTimeType();
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    public String getName()
    {
        return "local-date-time";
    }

}

然后在项目中配置上这个类型
引入model 配置那里

@Configuration
@EnableTransactionManagement
public class DataSourceConfig{
    @Bean(destroyMethod = "close")
    public DataSource dataSource()
    {
        return ConnectionManager.instance().createDataSource();
    }
    @Bean
    public SessionFactory sessionFactory()
    {
        LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(
                dataSource());
        builder.scanPackages();
        builder.registerTypeOverride(StringVarbinaryType.INSTANCE);//这个是之前对应数据库 varbinary 自定义 @type("string-binary")的解决
        builder.registerTypeOverride(LocalDateTimeType.INSTANCE);//这个是加载自定义时间的
        return builder.buildSessionFactory();
    }
}

最后在需要自定义格式的字段上注解这个type就可以了

@Column(name = "create_time",insertable = false,updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@Type(type = "local-date-time")
private LocalDateTime create_time;

最后返回就是这样的

 "create_time": "2016-09-02 11:59:07"

这篇关于java - hibernate 时间类型转换,date 属性的时间字段取出来后变样了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆