Pregunta

I have a webservice that will be persisting and deleting data to a Database. I want to track in the database which usernames touched which rows of the database. In each table there are columns for usernames to be stored (update columns if you will). There are also triggers on the tables that will take a userID for the transaction and update that table with the username and password that attempted to insert. Is there a way in open JPA where I can get the username (which will be passed from the client) and update some kind of JPA object so that when JPA persists data, that user name will be thrown into the table?

¿Fue útil?

Solución

One of the cleanest ways is to implement a common "mapped" superclass for your entities and use a method with @PrePersist annotation to populate the fields.

@MappedSuperclass
public class AuditedEntity {
    @Id protected Integer id;
    protected String lastUpdatedBy;

    // Setters and getters here

    @PreUpdate
    @PrePersist
    public void onChange() {
        String user = .... // Do whatever is needed to get the current user
        setLastUpdatedBy(user);
    }
}


@Entity
public class Employee extends AuditedEntity {
    // ....
} 

Another option is to use a separate listener:

public interface AuditedEntity {
    public static void setLastUpdatedBy(String username);
}

@Entity
@EntityListeners({ MyLogger.class, ... })
public class Employee implements AuditedEntity {
    // ...
}

public class MyLogger {
    @PreUpdate
    @PrePersist
    public void onChange(Object o) {
        if(o instanceof AuditedEntity) {
            String user = .... // Do whatever is needed to get the current user
            ((AuditedEntity) o).setLastUpdatedBy(user);
        }
    }

    @PostPersist
    @PostUpdate
    public void logChange(Object o) {
        // Log the successful operation
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top