Java MCQ: Which annotation is used to mark a class as an entity listener in JPA?
Answer:
Explanation:
The @EntityListeners
annotation in JPA is used to mark a class or method as an entity listener. Entity listeners are used to intercept entity lifecycle events such as prePersist
, postPersist
, preUpdate
, postUpdate
, preRemove
, postRemove
, and postLoad
. By defining an entity listener, you can add custom logic that executes automatically when these events occur.
Here’s an example:
@EntityListeners(AuditListener.class)
@Entity
public class Employee {
@Id
private Long id;
private String name;
// Getters and setters
}
public class AuditListener {
@PrePersist
public void prePersist(Employee employee) {
System.out.println("Before persisting: " + employee.getName());
}
}
In this example, the AuditListener
class is defined as an entity listener using the @EntityListeners
annotation. The prePersist
method will be called before the Employee
entity is persisted to the database.
Entity listeners are powerful tools in JPA for handling cross-cutting concerns such as auditing, logging, or validation.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html