or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

caching-locking.mdcriteria-api.mdentity-manager.mdentity-mapping.mdindex.mdlifecycle-callbacks.mdmetamodel.mdqueries.mdspi.md

lifecycle-callbacks.mddocs/

0

# Lifecycle Callbacks

1

2

Complete reference for entity lifecycle event callbacks and listeners in Jakarta Persistence.

3

4

## Imports

5

6

```java { .api }

7

import jakarta.persistence.*;

8

```

9

10

## Capabilities

11

12

### Lifecycle Callback Annotations

13

14

Hook into entity lifecycle events.

15

16

```java { .api }

17

/**

18

* Specifies a callback method for the corresponding lifecycle event

19

*/

20

@Target({METHOD})

21

@Retention(RUNTIME)

22

public @interface PrePersist {}

23

24

@Target({METHOD})

25

@Retention(RUNTIME)

26

public @interface PostPersist {}

27

28

@Target({METHOD})

29

@Retention(RUNTIME)

30

public @interface PreUpdate {}

31

32

@Target({METHOD})

33

@Retention(RUNTIME)

34

public @interface PostUpdate {}

35

36

@Target({METHOD})

37

@Retention(RUNTIME)

38

public @interface PreRemove {}

39

40

@Target({METHOD})

41

@Retention(RUNTIME)

42

public @interface PostRemove {}

43

44

@Target({METHOD})

45

@Retention(RUNTIME)

46

public @interface PostLoad {}

47

48

/**

49

* Specifies callback listener classes

50

*/

51

@Target({TYPE})

52

@Retention(RUNTIME)

53

public @interface EntityListeners {

54

Class[] value();

55

}

56

57

/**

58

* Exclude default listeners

59

*/

60

@Target({TYPE})

61

@Retention(RUNTIME)

62

public @interface ExcludeDefaultListeners {}

63

64

/**

65

* Exclude superclass listeners

66

*/

67

@Target({TYPE})

68

@Retention(RUNTIME)

69

public @interface ExcludeSuperclassListeners {}

70

```

71

72

**Usage Example:**

73

74

```java

75

@Entity

76

@EntityListeners({AuditListener.class, ValidationListener.class})

77

public class User {

78

@Id

79

private Long id;

80

private String name;

81

private LocalDateTime createdAt;

82

private LocalDateTime updatedAt;

83

84

@PrePersist

85

protected void onCreate() {

86

createdAt = LocalDateTime.now();

87

}

88

89

@PreUpdate

90

protected void onUpdate() {

91

updatedAt = LocalDateTime.now();

92

}

93

94

@PostLoad

95

protected void onLoad() {

96

// Initialize transient fields

97

}

98

}

99

100

public class AuditListener {

101

@PrePersist

102

public void prePersist(Object entity) {

103

// Audit logging

104

}

105

106

@PostPersist

107

public void postPersist(Object entity) {

108

// Post-persist actions

109

}

110

}

111

```

112

113

[Complete documentation in index.md](./index.md)

114