Typical Entity Life-cycle
JPA provides total of 6 Annotations for Life-Cycle Callback events.
This is how we can use the above annotations.
Solution 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.
}
}
Solution 2 : Using Entity Listeners Classes
This is very nice way of using the annotations. Clean code and same rules from above applies.
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 - Saving 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
This is how we can use the above annotations.
Solution 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.
}
}
Solution 2 : Using Entity Listeners Classes
This is very nice way of using the annotations. Clean code and same rules from above applies.
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
if you have any tutorial e-book then just sent link to the link
jazz.pethani@gmail.com