EclipseLink描述符定制器和历史策略以及JSF.如何在历史记录中插入用户主体?

Han*_*sky 3 jsf jpa eclipselink java-ee

在我的JSF Web应用程序中,我使用EclipseLink

描述符定制器

历史政策

填充数据库中的历史表.相应的JPA实体类使用注释@Customizer(beans.HistoryLesionhCustomizer.class)

历史表与源表具有相同的字段,另外还有两个字段(start_date和end_date),用于指定行的操作的开始和结束.它完全有效.但我需要的是填充历史表中的另一个字段.我调用user的这个字段应填充用户主体,这样我就可以跟踪执行CUD(创建/更新/删除)操作的用户.我认为历史策略允许我通过在数据库中指示其对应的名称来添加字段,并指示必须插入的对象值.但情况并非如此,或者可能是我无法弄清楚如何做到这一点.换句话说,与start_date和end_date一起,我想用以下内容填充用户字段:

.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)



    }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助或解决方法将不胜感激.谢谢

Mat*_*ndy 7

不幸的是HistoryPolicy只添加开始和结束日期.但是您可以借助于实体向您的实体添加用户信息EntityListeners.这是一个例子.它会将用户信息添加到customer表的每个持久化/更新中:

import javax.persistence.EntityListeners;

@Entity
@EntityListeners(AuditListener.class)
@Table(name = "customer")
public class Customer implements Serializable {
  @Column(name = "User")
  private String user;
  // getter and setter
}
Run Code Online (Sandbox Code Playgroud)

和AuditListener:

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
//...

public class AuditListener {
    @PrePersist
    @PreUpdate
    public void setUserInformation(Object entity) {
        if (entity instanceof Customer) {
            Customer myEntity = (Customer) entity;
            myEntity.setUser(FacesContext.getCurrentInstance().getExternalContext().getRemoteUser());

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您有多个需要用户信息的列,则可以使用MappedSuperclass实体并将user列放在此类中.然后让所有可审计实体扩展此MappedSuperclass,并检查AuditListener是否该实体是超类的实例.