JPA - Lifecycle Callback Listener Annotations

Code Snippets JPA JAVA EE 

import javax.persistence.*;

@Entity
public class MyEntity {
@Id
@GeneratedValue
private int id;
private String msg;

public MyEntity() { }

public MyEntity(String msg) {
this.msg = msg;
}

@PrePersist
void onPrePersist() {
System.out.println("MyEntity.onPrePersist()");
}

@PostPersist
void onPostPersist() {
System.out.println("MyEntity.onPostPersist()");
}

@PostLoad
void onPostLoad() {
System.out.println("MyEntity.onPostLoad()");
}

@PreUpdate
void onPreUpdate() {
System.out.println("MyEntity.onPreUpdate()");
}

@PostUpdate
void onPostUpdate() {
System.out.println("MyEntity.onPostUpdate()");
}

@PreRemove
void onPreRemove() {
System.out.println("MyEntity.onPreRemove()");
}

@PostRemove
void onPostRemove() {
System.out.println("MyEntity.onPostRemove()");
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}
}
Original Post




import javax.persistence.*;
import java.sql.Timestamp;
import java.time.Instant;

@Entity
public class Article {
@Id
@GeneratedValue
private int id;
private String content;
private Timestamp dateCreated;
private Timestamp lastUpdated;

@PrePersist
void preCreate() {
dateCreated = Timestamp.from(Instant.now());
lastUpdated = Timestamp.from(Instant.now());
}

@PreUpdate
void preUpdate() {
lastUpdated = Timestamp.from(Instant.now());
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

@Override
public String toString() {
return "Article{" +
"id=" + id +
", content='" + content + '\'' +
", dateCreated=" + dateCreated +
", lastUpdated=" + lastUpdated +
'}';
}
}
Original Post




See Also