In my JSF web application, I use EclipseLink
Descriptor Customizer
and
History Policy
to populate a history table in database.
The corresponding JPA entity class is annotated with @Customizer(beans.HistoryLesionhCustomizer.class)
The history table has the same fields as the source table, plus two fields (start_date & end_date) to specify the start and end of operation on a row.
It is fully working. But what I need is to populate another field in the history table.
This field I called user, should be populated with the User Principals, and this will allow me to trace the user who performed the CUD (Create/Update/Delete) operation.
I thought History Policy would allow me to add a field by just indicating its corresponding name in the database and indicate the object value that must be inserted. But that is not the case, or may it be I am not able to figure how this can be done.
In other words, along with start_date and end_date, i want to populate user field with :
FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
package beans;
/**
* Whenever there is a change on a record or an insert, change will be traced.
* @author mediterran
*
*/
import javax.faces.context.FacesContext;
import org.eclipse.persistence.config.DescriptorCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.history.HistoryPolicy;
public class HistoryLesionhCustomizer implements DescriptorCustomizer {
@Override
/**
* Implementation method to use
*/
public void customize(ClassDescriptor cd) throws Exception {
String user = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
HistoryPolicy policy = new HistoryPolicy(); // Instantiates a new policy
//policy.postUpdate();
policy.useDatabaseTime(); // Use the default database time to avoid date conflict
policy.addHistoryTableName("history_lesionh"); // Indicate the source table name
policy.addStartFieldName("start_date"); // indicate the start date DB column
policy.addEndFieldName("end_date"); // Indicate the end date DB column
cd.setHistoryPolicy(policy); // Use the Policy for the entity class where used @Customizer(HistoryLesionhCustomizer.class)
}
}
Any help or workarounds would be appreciated.
Thanks
Unfortunately
HistoryPolicyonly adds start and end date. But you can add user information to your entity with the help of anEntityListeners. Here is an example. It will add user information to each persist/update of the customer table:and the AuditListener:
If you have more than one column that needs user information, you can use a MappedSuperclass entity and put the user column in this class. Then let all your auditable entities extend this MappedSuperclass and check in the AuditListener if the entity is an instance of the superclass.