LocalDateTime 的 JPA AttributeConverter

JPA AttributeConverter for LocalDateTime

我正在密切关注这些帖子 (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());
    }

}

这是实体class

@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中的方法class:

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

提前致谢。

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

transient

来自

private transient LocalDateTime createdAt;

SonarLint 需要它,因为 class 实现了 Serializable,这就是我把它放在第一位的原因。