I need to create an Audit table(not file), using JPA(Only Option)
Audit table means, Say on Delete event an entry to audit table would be pushed, stating the username, timestamp, etc. for auditing purpose for later. The method I have used is to have a listener class for the Entity. The listener class would fire the @PreRemove method. This is a callback call.
@Getter @Setter
@ToString @NoArgsConstructor
@Entity @AllArgsConstructor
@Table(name = "TableToBeAudited")
@EntityListeners(AuditListener.class)
public class TableToBeAudited implements Auditable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
....OTHER COLUMNS HERE
....
transient Audit audit;
@Override
public Audit getAudit() {
audit = new Audit();
audit.setEventType("Postings");
return audit;
}
Auditable Interface Definition:
public interface Auditable {
Audit getAudit();
void setAudit(Audit audit);
}
AuditListener.java Class
public class AuditListener {
private AuditRepository auditRepository = new AuditRepository();
@PreRemove
public void persistOnDeletion(Auditable auditable) {
try {
Audit audit = auditable.getAudit();
audit.setEventType("DELETE");
auditRepository.addAuditEntry(audit);
}catch(Exception e) {
System.out.println(e);
}
}
}
And lastly my AuditRepostory.java
import javax.persistence.PersistenceUnit;
import javax.transaction.Transactional;
@Transactional
@Repository
public class AuditRepository {
@PersistenceUnit(name = "unit")
EntityManagerFactory entityManagerFactory; /*This is coming null here. I have tried EntityManager also with @PersistenceContext. The null is probably because we cannot have another PersistenceContext within one persistenceContext. This is a call back call for the listner.*/
public void addAuditEntry(Audit audit) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction();
entityManager.persist(audit);
entityManager.getTransaction().commit();;
}
}
Now the main issue is The EntityManagerfactory or EntityManager that I wire via @PersistenceContext or @PersistenceUnit is wiring to null. I have tried all combinations of EntityManagerfactory,EntityManager with PersistenceContext and PersistenceUnit
My expectations :
- Solution/Improvement to this code.
- A new approach using JPA