简体   繁体   中英

JPA PrePersist and PreUpdate

I'm using a base entity:

@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

Then I have an entity:

@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 ...

Here is my test:

@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());
}

The test fails because the updated field does not get set. How do I do this? This is Hibernate JPA with arquillian and wildfly for testing.

As Alan Hay said, an em.flush() right before the persist works just fine in this case. It's not a duplicate of the question suggested, because flushing works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM