我想用接口的find方法,而不是在實現中使用。JPA:通過接口而不是實現來尋找
,這裏說的是我的代碼:
public Goods findGoods(Long goodsId) {
return this.jpaApi.withTransaction(()->{
Goods goods = null;
try{
EntityManager em = this.jpaApi.em();
Query query = em.createQuery("select g from Goods g where id=:id", Goods.class);
query.setParameter("id", goodsId);
goods = (Goods) query.getSingleResult();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return goods;
});
}
我的實體:
@Entity(name = "Goods")
@Table(name = "GOODS")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class GoodsImp implements Goods, Serializable {
..
}
我的接口:
@JsonTypeInfo(include = JsonTypeInfo.As.PROPERTY, property = "type",
use = Id.NAME, defaultImpl = GoodsImp.class, visible = true)
@JsonSubTypes({ @Type(value = ProductImp.class, name = "product"),
@Type(value = ServiceImp.class, name = "service") })
@ImplementedBy(GoodsImp.class)
public interface Goods {
..
}
錯誤:
java.lang.IllegalArgumentException: Unable to locate persister: interfaces.Goods at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3422) at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3365) at repository.JPAGoodsRepository.lambda$deleteGoods$2(JPAGoodsRepository.java:58) at play.db.jpa.DefaultJPAApi.lambda$withTransaction$3(DefaultJPAApi.java:197)
我的疑問是爲什麼我有這個問題,如果當我使用查詢語句與接口工作正常。
這工作:
@Override
public Collection<Goods> getAllGoods() {
return this.jpaApi.withTransaction(() -> {
Collection<Goods> goods = null;
try {
EntityManager em = this.jpaApi.em();
Query query = em.createQuery("Select g from Goods g", Goods.class);
goods = query.getResultList();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return goods;
});
}
JPA API不認爲接口值得持久性處理。 DataNucleus JPA確實允許那個JPQL,但是不知道其他任何人都這麼做,並且你無論如何都會參與供應商擴展 – DN1
因此,我只能在JPQL中使用接口,但不能在.find方法中使用? – Aleyango
正如我所說,JPA不考慮接口,所以如果堅持規範並且只有1個我知道的供應商支持它們,您就不能使用它們,但是您沒有使用它。 – DN1