JPA PrePersist和PreUpdate

时间:2016-05-20 13:55:42

标签: java hibernate jpa

我正在使用基本实体:

@MappedSuperclass
public class BaseEntity {
    private static final Logger L = LoggerFactory.getLogger(BaseEntity.class);

    String id;
    String name;
    String description;

    Date created;
    Date updated;

    public BaseEntity() {
        id = UUID.randomUUID().toString();
    }

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

    @PreUpdate
    protected void onUpdate() {
        updated = new Date();
    }

    @Id
    @Column(name = "id", nullable = false)
    public String getId() {
        return id;
    }

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

    @Temporal(TemporalType.TIMESTAMP)
    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    @Temporal(TemporalType.TIMESTAMP)
    public Date getUpdated() {
        return updated;
    }

    public void setUpdated(Date updated) {
        this.updated = updated;
    }
    ... snip

然后我有一个实体:

@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.UUIDGenerator.class, property = "@baby_id", scope = Baby.class)
@Table(name="babies")
public class Baby extends BaseEntity {
    private static final Logger L = LoggerFactory.getLogger(Baby.class);

    Date dob;

    public Baby() {
        super();
    }

    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }
    ... snip ...

这是我的测试:

@Test
@Transactional
public void testCreateBaby() {
    Baby b = new Baby();
    b.setName("n");
    b.setDescription("baby");
    b.setDob(new Date());

    assertNull(b.getCreated());
    assertNull(b.getUpdated());
    em.persist(b);
    assertNotNull(b);
    assertNotNull(b.getCreated());
    assertNull(b.getUpdated());

    b.setName("n3");
    b = em.merge(b);
    em.persist(b);
    assertNotNull(b.getUpdated());
}

测试失败,因为updated字段未设置。我该怎么做呢?这是带有arquillian和wildfly的Hibernate JPA进行测试。

1 个答案:

答案 0 :(得分:0)

正如Alan Hay所说,在这种情况下,持久性之前的em.flush()工作正常。这不是建议的问题的重复,因为冲洗工作。