我有一个 JPA 实体的类层次结构,它们都继承自 BaseEntity 类:
@MappedSuperclass
@EntityListeners( { ValidatorListener.class })
public abstract class BaseEntity implements Serializable {
// other stuff
}
我希望所有实现给定接口的实体都能在持久化和/或更新时自动验证。这就是我所拥有的。
我的验证器监听器:
public class ValidatorListener {
private enum Type {
PERSIST, UPDATE
}
@PrePersist
public void checkPersist(final Object entity) {
if (entity instanceof Validateable) {
this.check((Validateable) entity, Type.PERSIST);
}
}
@PreUpdate
public void checkUpdate(final Object entity) {
if (entity instanceof Validateable) {
this.check((Validateable) entity, Type.UPDATE);
}
}
private void check(final Validateable entity, final Type persist) {
switch (persist) {
case PERSIST:
if (entity instanceof Persist) {
((Persist) entity).persist();
}
if (entity instanceof PersistOrUpdate) {
((PersistOrUpdate) entity).persistOrUpdate();
}
break;
case UPDATE:
if (entity instanceof Update) {
((Update) entity).update();
}
if (entity instanceof PersistOrUpdate) {
((PersistOrUpdate) entity).persistOrUpdate();
}
break;
default:
break;
}
}
}
这是我检查的 Validateable 接口(外部接口只是一个标记,内部包含方法):
public interface Validateable {
interface Persist extends Validateable {
void persist();
}
interface PersistOrUpdate extends Validateable {
void persistOrUpdate();
}
interface Update extends Validateable {
void update();
}
}
所有这些都有效,但是我想将此行为扩展到 Embeddable 类。我知道两种解决方案:
从实体验证方法手动调用可嵌入对象的验证方法:
public void persistOrUpdate(){ // validate my own properties first // then manually validate the embeddable property: myEmbeddable.persistOrUpdate(); // this works but I'd like something that I don't have to call manually }
使用反射,检查所有属性以查看它们的类型是否属于它们的接口类型之一。这会起作用,但它并不漂亮。有没有更优雅的解决方案?