JPA @PrePersist在测试环境中

时间:2017-04-10 06:56:27

标签: java hibernate jpa dao

我有GenericEntity@PrePersist方法onCreate(),它在将实体保存到数据库之前设置时间戳。它运行良好但我在尝试测试我的DAO类时遇到了问题。保存实体时,@PrePersist会覆盖显式设置created字段值。如何在测试环境中使@PrePersist成为可选项,以便我可以明确设置created字段值?

@MappedSuperclass
public abstract class GenericEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created", nullable = false)
    private Date created;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @PrePersist
    protected void onCreate() {
        created = new Date();
    }

    /*
     * Used for tests
     */
    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getCreated() {
        return created;
    }
}

1 个答案:

答案 0 :(得分:2)

如果您允许访问set created value(通过setter),则不应在@PrePersist方法中覆盖此值。我认为解决问题的最简单方法是简单的无效检查:

@PrePersist
protected void onCreate() {
    if (created == null) {
        created = new Date();
    }
}