Typical Entity Life-cycle
JPA provides total of 6 Annotations for Life-Cycle Callback events.
Following two ways to utilize the above annotations.
Case 1: Defining inside Entity class
Any method can be annotated with one or all annotations, though they should follow these rules.
Example Code Snippet - 1
@Entity
public class Employee implements Serializable {
...
@PrePersist
@PostPersist
@PreUpdate
@PostUpdate
@PreRemove
@PostLoad
public void updateDate() {
// this method will executed on all the lifecycle events.
}
}
Way 2 : Using Entity Listeners Classes
This is very nice way of using the annotations.
Example Code Snippet - 2
@EntityListeners({LastAccessDateListener.class})
public class Employee implements NamedEntity {
...
}
public class LastAccessDateListener {
@PrePersist
@PostPersist
@PreUpdate
@PostUpdate
@PreRemove
@PostLoad
public void updateDate(Employee e) {
// this method is in totally separate class
}
}
- Persist - Creating Entity for the first time.
- Merge - Updating detached Entity
- Load - Loading Entity from Database
- Delete - Deleting Entity from Database
JPA provides total of 6 Annotations for Life-Cycle Callback events.
- @PrePersist
- @PostPersist
- @PreUpdate
- @PostUpdate
- @PreRemove
- @PostLoad
Following two ways to utilize the above annotations.
Case 1: Defining inside Entity class
Any method can be annotated with one or all annotations, though they should follow these rules.
- Method can have any name
- No parameters
- Return type of void
- Method should not be final or static
- No Checked exceptions should be thrown
- Any annotation can be only used on one method
Example Code Snippet - 1
@Entity
public class Employee implements Serializable {
...
@PrePersist
@PostPersist
@PreUpdate
@PostUpdate
@PreRemove
@PostLoad
public void updateDate() {
// this method will executed on all the lifecycle events.
}
}
Way 2 : Using Entity Listeners Classes
This is very nice way of using the annotations.
Example Code Snippet - 2
@EntityListeners({LastAccessDateListener.class})
public class Employee implements NamedEntity {
...
}
public class LastAccessDateListener {
@PrePersist
@PostPersist
@PreUpdate
@PostUpdate
@PreRemove
@PostLoad
public void updateDate(Employee e) {
// this method is in totally separate class
}
}
LastAccessDateListener class doesn't have to be annotated or extend any other class.
Comments