我正在密切关注这些帖子(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;
...
}
这是我在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
提前谢谢。
答案 0 :(得分:-2)
我现在就开始工作了。我删除了
瞬态
这
private transient LocalDateTime createdAt;
SonarLint要求它,因为该类实现了Serializable,这就是为什么我把它放在首位。