我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