2013-05-02 20 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); 
    } 
相关问题