在JPA

2015-09-25 25 views
0

返回列表類型我有DTO結構,如:在JPA

public class ADto{ 
    private String name; 
    private String id; 
    private List<BDto> bdtos; 

//Created constructor using fields 
} 

public class BDto{ 
    private String id; 
    private String code; 
    private List<CDto> cdtos; 

//Created constructor using fields 
} 

public class CDto{ 
    private String mKey; 
    private String mVal; 

//Created constructor using fields 
} 

使用Spring MVC的用於獲取數據。

下面的查詢工作完全正常,並結合數據:

@org.springframework.data.jpa.repository.Query("select new pkg.ADto(id,name) from AEntity a where a.id=?1") 
public ADto getAData(Long id); 

我怎樣才能獲取數據,其又使用上述方法還列表組成的列表?

+0

想要在提取單個ADto時返回'BDto'列表? –

+0

@BranislavLazic是的.. – xyz

回答

1

如果你想在enitites而不是返回的DTO,您需要提供之間的映射:

@OneToMany(mappedBy = "adto", fetch = FetchType.EAGER) 
private List<BDto> bdtos; 

然後,你可以這樣即把它拿來DTO和實體。使用JPQL查詢,唯一的選擇是在結果對象的構造函數中提供該映射。因此,您需要向ADto添加構造函數,該構造函數接受BEntities,並將所有嵌套實體映射到該構造函數中的dtos。或者更多面向對象的方式,新的構造函數將接受AEntity作爲唯一的參數。

這是怎麼可能看起來像:

getAData()方法庫(JPQL略微加入a.bEntities導致修改):

@org.springframework.data.jpa.repository.Query("select new pkg.ADto(id,name, a.bEntities) from AEntity a where a.id=?1") 
public ADto getAData(Long id); 

新的構造在ADto:

public class ADto{ 
    private String name; 
    private String id; 
    private List<BDto> bdtos; 

    public ADto(String id, String name, List<BEntity> bEntities) { 
    this.id = id; this.name = name; 
    this.bdtos = new ArrayList<>(); 
    for (BEntity b : bEntities) { 
     BDto bdto = new BDto(b.id, b.code, b.cEntities); 
    /* you need to pass cEntities and map them again in the BDto 
    * constructor, or you may do the apping in ADto constructor 
    * and only pass mapped values to BDto constructor */ 
    } 
    } 
} 
0

您必須啓用預先抓取:

ADto findById(Long id); // literally! 
+0

只是還有一件事.. adto和Bdto沒有實體,只是dtos ..應該推薦使用這種方式,並將工作? – xyz

+0

您必須爲'BDto'定義新的屬性:'私人ADto adto;'(使用getter和setter)。正確註釋類。 –