Hibernate 如何将Long映射到列datetime
我的列类型是datetimeHibernate 如何将Long映射到列datetime,hibernate,Hibernate,我的列类型是datetime `firstExpressTime` datetime NOT NULL , 我的财产很长 我用 但当我保存实体时,它会报告Exception 如何解决?提前感谢您的帮助和建议。因为在数据库中使用了datetime,所以您需要在java/Hibernate代码中使用java.util.Date 但是,我相信这不会有太大问题,因为您可以通过调用getTime()随时获取底层时间戳 您应该使用AttributeConverter。对长字段进行如下注释: @Conver
`firstExpressTime` datetime NOT NULL ,
我的财产很长
我用
但当我保存实体时,它会报告Exception
如何解决?提前感谢您的帮助和建议。因为在数据库中使用了datetime,所以您需要在java/Hibernate代码中使用java.util.Date 但是,我相信这不会有太大问题,因为您可以通过调用getTime()随时获取底层时间戳
您应该使用AttributeConverter。对长字段进行如下注释:
@Convert(converter = DateToLongConverter.class)
private Long birthdate;
并创建您的转换器类:
@Converter
public class DateToLongConverter implements AttributeConverter<Long, Date> {
@Override
public Date convertToDatabaseColumn(Long attribute) {
return new Date(attribute);
}
@Override
public Long convertToEntityAttribute(Date dbData) {
return dbData.getTime();
}
}
@转换器
公共类DateToLongConverter实现AttributeConverter{
@凌驾
公共日期convertToDatabaseColumn(长属性){
返回新日期(属性);
}
@凌驾
公共长convertToEntityAttribute(Date dbData){
返回dbData.getTime();
}
}
DbHibernateObj obj = service.getMyObject(id);
long timestamp = obj.getFirstExpressTime().getTime();
@Convert(converter = DateToLongConverter.class)
private Long birthdate;
@Converter
public class DateToLongConverter implements AttributeConverter<Long, Date> {
@Override
public Date convertToDatabaseColumn(Long attribute) {
return new Date(attribute);
}
@Override
public Long convertToEntityAttribute(Date dbData) {
return dbData.getTime();
}
}