AttributeConverter日期字符串 [英] AttributeConverter Date String

查看:72
本文介绍了AttributeConverter日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建AttributeConverter<Date,String>?我想在Hibernate的Spring项目中使用它. 我想将String dataColumn转换为Date实体属性. 请帮我. 与休眠方式扫描相比,它放置在软件包中的位置很好

Is it possible to create AttributeConverter<Date,String>? I want to use it in a Spring project with Hibernate. I want to convert String dataColumn to Date entity attribute. Please help me. It is well placed in package than is scanned by hibernate

@Converter(autoApply=true)
public class DatetoStringConverter implements AttributeConverter
{
    @Override
    public String convertToDatabaseColumn(Date arg0) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy",Locale.FRENCH);
        return formatter.format(arg0);
    }

    @Override
    public Date convertToEntityAttribute(String arg0) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy",Locale.FRENCH);
            return  formatter.parse(arg0);
        } catch (ParseException e) {
            return null;
        }
    }
}

和字段

@Column(name="Date")
@DateTimeFormat(pattern="dd/MM/yyyy")
@Convert(converter=DatetoStringConverter.class)
private Date datefonction;

推荐答案

定义转换器:

@Converter(autoApply = true)
public class MyDateAttributeConverter implements AttributeConverter<Date, String> {

    @Override
    public String convertToDatabaseColumn(Date entityDate) {
        // format entityDate and return String
    }

    @Override
    public Date convertToEntityAttribute(String databaseDate) {
        // parse databaseDate and return Date object
    }
}

将转换器应用于您实体中的所需字段:

Apply converter to the desired field in your entity:

@Convert(converter = MyDateAttributeConverter.class)
private Date date;

只需确保将@AttribureConverter放置在一个包中,而不是将其休眠(会话工厂属性)即可.

Just make sure that the @AttribureConverter is placed in a package than is scanned by hibernate (session factory property).

这篇关于AttributeConverter日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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