2020-04-18

Hibernate JPA @PostPersist Example

@PostPersist

The @PostPersist annotation is used to specify a callback method that fires after an entity is persisted.

PostPersist Specifies a callback method for the corresponding lifecycle event. This annotation may be applied to methods of an entity class, a mapped superclass, or a callback listener class.

Example of specifying JPA callbacks

@Entity
@EntityListeners( LastUpdateListener.class )
public static class Person {

@Id
private Long id;

private String name;

private Date dateOfBirth;

@Transient
private long age;

private Date lastUpdate;

public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}

/**
* Set the transient property at load time based on a calculation.
* Note that a native Hibernate formula mapping is better for this purpose.
*/
@PostLoad
public void calculateAge() {
age = ChronoUnit.YEARS.between( LocalDateTime.ofInstant(
Instant.ofEpochMilli( dateOfBirth.getTime()), ZoneOffset.UTC),
LocalDateTime.now()
);
}
}

public static class LastUpdateListener {

@PreUpdate
@PrePersist
public void setLastUpdate( Person p ) {
p.setLastUpdate( new Date() );
}
}

No comments:

Post a Comment