【问题标题】:JPA AttributeConverter for LocalDateTimeLocalDateTime 的 JPA AttributeConverter
【发布时间】: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


    【解决方案1】:

    我现在开始工作了。我删除了

    瞬态

    来自

    private transient LocalDateTime createdAt;
    

    SonarLint 需要它,因为该类实现了 Serializable 这就是我首先提出它的原因。

    【讨论】:

    • 是的。我错过了。
    • 如果您不发布实际代码,您希望别人如何帮助您?
    • 我只是为了保密而尽量小心。我无法发布实际代码。我什至替换了类名。我的错我排除了“瞬态”。
    • 顺便说一句,谢谢(在我弄明白之前,您可能已经开始努力回答这个问题了)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 2014-07-31
    • 1970-01-01
    • 2020-12-25
    • 2021-01-19
    • 1970-01-01
    • 2014-04-17
    相关资源
    最近更新 更多