Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使JPA EntityListeners验证接口的存在_Jpa_Entitylisteners - Fatal编程技术网

如何使JPA EntityListeners验证接口的存在

如何使JPA EntityListeners验证接口的存在,jpa,entitylisteners,Jpa,Entitylisteners,我使用JPA在J2EE5中工作,我有一个可行的解决方案,但我希望清理结构 我在一些持久化的JPA对象上使用EntityListeners,这些侦听器相当通用,但依赖于实现接口的bean,如果您记得添加接口,这将非常有用 我无法确定将EntityListener和接口绑定在一起的方法,以便得到一个指向正确方向的异常,或者更好的是一个编译时错误 @Entity @EntityListener({CreateByListener.class}) public class Note implements

我使用JPA在J2EE5中工作,我有一个可行的解决方案,但我希望清理结构

我在一些持久化的JPA对象上使用EntityListeners,这些侦听器相当通用,但依赖于实现接口的bean,如果您记得添加接口,这将非常有用

我无法确定将EntityListener和接口绑定在一起的方法,以便得到一个指向正确方向的异常,或者更好的是一个编译时错误

@Entity
@EntityListener({CreateByListener.class})
public class Note implements CreatorInterface{
    private String message;....
    private String creator;
    ....
}

public interface CreatorInterface{
    public void setCreator(String creator);
}

public class CreateByListener {
    @PrePersist
    public void dataPersist(CreatorInterface data){
        SUser user = LoginModule.getUser();
        data.setCreator(user.getName());
    }
}
这个函数完全按照我希望的方式运行,除非创建了一个新类,并且它使用CreateByListener,但没有实现CreatorInterface。 当这种情况发生时,一个类强制转换异常会从JPA引擎中的某个深处抛出,只有当我碰巧记得这个症状时,我才能找出哪里出了问题

在启动侦听器之前,我无法找到一种方法来要求接口或测试接口是否存在

任何想法都将不胜感激

@PrePersist
public void dataPersist(Object data){
    if (!(data instanceof CreatorInterface)) {
        throw new IllegalArgumentException("The class " 
                                           + data.getClass() 
                                           + " should implement CreatorInterface");
    }
    CreatorInterface creatorInterface = (CreatorInterface) data;
    SUser user = LoginModule.getUser();
    creatorInterface.setCreator(user.getName());
}
这与您正在做的事情基本相同,但至少您会有一个更可读的错误消息来指示错误,而不是ClassCastException