简体   繁体   English

如何使用JPA在Java中将MySQL时间戳字段保留为长(纪元)字段?

[英]How do I persist a MySQL timestamp field as a long (epoch) field in java using JPA?

I have a column in a MySQL table like: 我在MySQL表中有一列,例如:

createdAt timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP`.

I want it to be stored in a field like: 我希望将其存储在如下字段中:

private Long createdAt;

How would I do this? 我该怎么做?

Best if you use the supported types in TemporalType enum. 如果您在TemporalType枚举中使用受支持的类型,则最好。 Longs would require a converter. 多头需要转换器。

Here's a converter for longs: 这是一个长期的转换器:

import java.sql.Timestamp;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class LongConverter implements AttributeConverter<Long, Timestamp> {

   @Override
   public Timestamp convertToDatabaseColumn(Long attribute) {
      if (attribute == null)
         return null;
      return new Timestamp(attribute);
   }

   @Override
   public Long convertToEntityAttribute(Timestamp dbData) {
      if (dbData == null)
         return null;
      return dbData.getTime();

   }

}

简单地使用@Temporal(TemporalType.TIMESTAMP)以上createdAt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM