Jakarta Persistence API provides a comprehensive framework for object-relational mapping, entity lifecycle management, and database operations in Java applications
Complete reference for entity lifecycle event callbacks and listeners in Jakarta Persistence.
import jakarta.persistence.*;Hook into entity lifecycle events.
/**
* Specifies a callback method for the corresponding lifecycle event
*/
@Target({METHOD})
@Retention(RUNTIME)
public @interface PrePersist {}
@Target({METHOD})
@Retention(RUNTIME)
public @interface PostPersist {}
@Target({METHOD})
@Retention(RUNTIME)
public @interface PreUpdate {}
@Target({METHOD})
@Retention(RUNTIME)
public @interface PostUpdate {}
@Target({METHOD})
@Retention(RUNTIME)
public @interface PreRemove {}
@Target({METHOD})
@Retention(RUNTIME)
public @interface PostRemove {}
@Target({METHOD})
@Retention(RUNTIME)
public @interface PostLoad {}
/**
* Specifies callback listener classes
*/
@Target({TYPE})
@Retention(RUNTIME)
public @interface EntityListeners {
Class[] value();
}
/**
* Exclude default listeners
*/
@Target({TYPE})
@Retention(RUNTIME)
public @interface ExcludeDefaultListeners {}
/**
* Exclude superclass listeners
*/
@Target({TYPE})
@Retention(RUNTIME)
public @interface ExcludeSuperclassListeners {}Usage Example:
@Entity
@EntityListeners({AuditListener.class, ValidationListener.class})
public class User {
@Id
private Long id;
private String name;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
@PostLoad
protected void onLoad() {
// Initialize transient fields
}
}
public class AuditListener {
@PrePersist
public void prePersist(Object entity) {
// Audit logging
}
@PostPersist
public void postPersist(Object entity) {
// Post-persist actions
}
}Install with Tessl CLI
npx tessl i tessl/maven-jakarta-persistence--jakarta-persistence-api