1

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.

mikeb
  • 10,578
  • 7
  • 62
  • 120
  • 2
    Try forcing a flush. Could be the case that the callback is not executed until just before flush. – Alan Hay May 20 '16 at 14:09
  • Possible duplicate of [@PreUpdate and @Prepersist in hibernate/JPA (using session)](http://stackoverflow.com/questions/4133287/preupdate-and-prepersist-in-hibernate-jpa-using-session) – sauumum May 20 '16 at 14:10
  • Please see http://forum.spring.io/forum/spring-projects/data/46235-hibernate-3-2-persistent-lifecycle-annotations-not-work if it help – sauumum May 20 '16 at 14:11
  • `em.flush()` does the trick – mikeb May 20 '16 at 14:16

1 Answers1

0

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.

mikeb
  • 10,578
  • 7
  • 62
  • 120