【发布时间】:2018-01-21 09:54:40
【问题描述】:
我正在密切关注这些帖子(https://www.thoughts-on-java.org/persist-localdate-localdatetime-jpa/、https://github.com/lbtc-xxx/jpa21converter)以实现从 JPA 2.1 sql.Timestamp 到 LocalDateTime 的转换器,反之亦然。
但是,我的转换器似乎无法正常工作。似乎它永远不会被调用,因为 sysout 不会打印出任何东西。
这是我的转换器:
import java.sql.Timestamp;
import java.time.LocalDateTime;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp>{
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime localDateTime) {
System.out.println("CONVERTER TIMESTAMPS: " + localDateTime);
return (localDateTime == null ? null : Timestamp.valueOf(localDateTime));
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
System.out.println("CONVERTER TIMESTAMPS: " + timestamp);
return (timestamp == null ? null : timestamp.toLocalDateTime());
}
}
这是实体类
@Entity
@Table(name = "survey")
public class Question {
@Id
@GeneratedValue(strategy = Generationtype.AUTO)
private Integer id;
...
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
/*I also tried here: @Convert(converter = LocalDateTimeConverter.class))*/
private LocalDateTime createdAt;
...
}
这是我在 May DAO 类中的方法:
TypedQuery<Question> query = em.createQuery("SELECT q FROM Question q", Question.class);
query.getResultList().forEach(question -> {
LOGGER.info("{}|{}|{}", question.getId(), question.getDescription(), question.getCreatedAt());
});
return query.getResultList();
打印出来:
1|hello|null
2|hi|null
3|howdy|null
提前谢谢你。
【问题讨论】:
标签: hibernate date jpa converter