Lifecycle Annotations Flashcards

1
Q

What

A

Lifecycle annotations allow you to hook into an entity’s lifecycle and execute custom logic at specific lifecycle events. These annotations are methods in the entity class that the persistence provider automatically calls.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

@PrePersist

A

Called before an entity is persisted.
Useful for initializing or validating fields before saving.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

@PostPersist

A

Called after an entity has been persisted.
Useful for logging or triggering additional processes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

@PreUpdate

A

Called before an entity is updated.
Useful for setting fields like lastModified.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

@PostUpdate

A

Called after an entity is updated

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

@PreRemove

A

Called before an entity is removed.
Useful for cleanup tasks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

@PostRemove

A

Called after an entity is removed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

@PostLoad

A

Called after an entity is loaded from the database.
Useful for initializing transient fields.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Example

A

@Entity
public class Order {
@Id
@GeneratedValue
private Long id;

@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderItem> items = new ArrayList<>();

@PrePersist
public void prePersist() {
    System.out.println("Preparing to persist order: " + this);
}

@PostPersist
public void postPersist() {
    System.out.println("Order persisted: " + this);
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly