Which annotation is used to mark a class as an entity listener in JPA?

Java MCQ: Which annotation is used to mark a class as an entity listener in JPA?

a) @EntityListener
b) @Entity
c) @Listener
d) @EntityListeners

Answer:

d) @EntityListeners

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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top