我JPA实体的类层次结构,所有从BaseEntity类继承:JPA entitylisteners和@Embeddable
@MappedSuperclass
@EntityListeners({ ValidatorListener.class })
public abstract class BaseEntity implements Serializable {
// other stuff
}
我想验证实现给定的接口的所有实体自动对坚持和/或更新。这是我得到的。
我ValidatorListener:
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 }
使用反射,检查所有的属性,看看他们的类型之一他们的接口类型。这会奏效,但并不漂亮。有没有更优雅的解决方案?
这是JPA 1还是2? – 2010-06-01 09:29:14
方法1似乎很好,我没有看到它有什么问题。 – ewernli 2010-06-01 09:45:41
@shervin jpa2,但我不认为这有什么区别,@ewernli:我想要一个自动化的解决方案,我希望它为嵌入式工作,就像实体和mappersperperclass – 2010-06-01 09:58:56