2013-05-02 21 views
1

我有一個2部分的問題得到一個特定的子實體:如何在JPA父AGG其中可能有許多孩子

  1. 我有了孩子的實體,而且有可能是根AGG他們中有很多人。我正在尋找一種有效的方法來獲得特定的一種。現在唯一的方法是將它們全部加載到內存中,然後再查看它們。我想要的基本上是通過索引從數據庫中獲取它們。有沒有辦法通過類直接做到這一點,而無需加載所有的子實體?

  2. 爲了解決Q1問題,我做了一個存儲庫的方法來做到這一點,但我顯然沒有正確地命名爲春做自動生成。我使用JPA /我和春天有以下庫:

    public interface FooBarRepository extends CrudRepository<FooBar, Long>{ 
        SomeEntityThatIsAChildEntityOfTheRootAggFooBar findItemByFooBarAndOtherItem(FooBar foobar, OtherItem otherItem); 
    } 
    

的問題是,這是不行的,春天拋出一個異常,說明它不能被稱爲FooBar的

財產
FactoryBean threw exception on object creation; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property order found for type com.bla.foobar.FooBar 

我試過使用'This'和'Id',並希望這些工作,但他們都沒有工作。

我試圖使用JPQL來得到它,但這不起作用,或者因爲子實體不知道它的父代,儘管子實體表實際上包含父代的FK。

回答

0

嘗試用本機查詢,像:

public Child findChildByIndex(Parent parent, int index) { 
     return (Child) em.createNativeQuery("SELECT * FROM childs WHERE parent_id = ?" , Child.class) 
       .setParameter(0, parent.getId()) 
       .setFirstResult(index) 
       .setMaxResults(1) 
       .getResultList().get(0); 
    } 
相關問題