我正在使用JPA在J2EE 5中工作,我有一个有效的解决方案,但我希望清理结构。
我正在持久化的一些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引擎内部会抛出一个类强制转换异常,只有当我碰巧记得这个症状时,我才能找出哪里出了问题。
我还没有想出一种方法来要求接口,或者在触发侦听器之前测试接口是否存在。
任何想法都将不胜感激。
发布于 2011-09-14 19:52:01
@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。
https://stackoverflow.com/questions/7415734
复制相似问题