LocalDateTime的JPA AttributeConverter

问题描述:

我正在密切关注这些帖子(https://www.thoughts-on-java.org/persist-localdate-localdatetime-jpa/,https://github.com/lbtc-xxx/jpa21converter)以实现从JPA 2.1 sql.Timestamp到LocalDateTime的转换器,反之亦然。LocalDateTime的JPA AttributeConverter

但是,它看起来像我的转台不起作用。它似乎从来没有被称为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; 
    ... 
} 

这是我在5月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 

预先感谢您。

我现在工作。我删除

短暂

private transient LocalDateTime createdAt; 

因为类实现Serializable,这就是为什么我把它放在第一SonarLint是需要它。

+0

你的问题甚至没有包含“瞬态”这个词...... –

+0

是的。我错过了它。 –

+0

如果你没有发布实际的代码,你期望有人能帮助你吗? –