I have two classes -
Employee.java
@Entity(name="EMPLOYEE")
@EntityListeners(value = { EmployeeLog.class })
public class Employee implements Serializable{
@Id @GeneratedValue
@Column(name="EMP_ID")
private int empID;
@Column(name="EMP_NAME")
private String empName;
public int getEmpID() {
return empID;
}
public void setEmpID(int empID) {
this.empID = empID;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
}
EmployeeLog.java
import java.io.Serializable;
import javax.persistence.PostUpdate;
import javax.persistence.PreUpdate;
public class EmployeeLog implements Serializable{
@PreUpdate
public void logPreUpdate(Employee e) {
System.out.println("Before database SAVE/UPDATE operation.");
}
@PostUpdate
public void logPostUpdate(Employee e) {
System.out.println("After database SAVE/UPDATE operation.");
}
}
I want EmployeeLog listener to be invoked on Employee class whenever Employee is updated. Problem is, my listener is not getting invoked. This is my testing code -
Session session = factory.openSession();
session.beginTransaction();
Employee emp = (Employee) session.get(Employee.class, 1);
System.out.println("Employee :::::::::::"+emp.getEmpName());
emp.setEmpName("John Doe Modified");
session.update(emp);
System.out.println("Employee updated::::"+emp.getEmpName());
session.getTransaction().commit();
session.close();
I found this article related to EntityListener EntityLIstener not called via OneToOne mapping with cascade
In this article there is a comment-
I suspect that the above setup doesn't work because the Application object is not actually changed, so that's why @prePersist and @PreUpdate don't get invoked.
Here I am changing my Employee object through setter method before calling update method but this doesn't work. When exactly listener is called? Will it be executed if I update Employee through update query?
Am I getting it completely wrong?