2012-08-15 96 views
0

我已經走了兩個實體與雙向onetomany關聯。我想使用帶有投影的標準(僅從少數列中獲取數據)獲得許多帶有許多Adress的許多Person。查詢結果我想放入List<Map<String, Object>>。結果列表應該有這樣的結構(地址數據應在父地址對象List<Map<String, Object>>包含):準則,預測,ALIAS_TO_ENTITY_MAP

[ 
    { 
    name: "Andrew" 
    surname: "..." 
    adress : [ 
     { 
      city : "New York" 
      street : "..." 
      type : "home" 
     } 
     { 
      city : "..." 
      street : "..." 
      type : "work: 
     } 
    ] 
    { 
    name: "..." 
    surname : "..." 
    address : [{....}] 
    } 
] 

實體:

public class Person{ 
    private Long id; 
    private String name; 
    private String surname; 
    private Integer age; 
    private String phoneNr; 

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "person", fetch = FetchType.LAZY) 
    private List<Address> addresses 

    // getters and setters 
} 


public class Address{ 
    private Long id; 
    private String city; 
    private String street; 
    @ManyToOne(fetch=FetchType.LAZY) 
@JoinColumn(name="person_id") 
    private Person person; 


    // getters and setters 
} 

所有我能做到是加載整個實體,哪些不符合我的需求。

Criteria criteria = currentSession().createCriteria(Person.class); 
criteria.setFetchMode("addresses", FetchMode.JOIN); 
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); 

任何建議將是非常有益的。

回答

0

我不認爲有可能從查詢返回List<Map<String, Object>>。 最簡單的方式來獲取你想要的是手動創建它的結構(至少我是這麼認爲的):

List<Map<String, Object>> resultsList = new ArrayList<Map<String, Object>>(); 
List<Person> persons = criteria.list(); 

for (Person person: persons) { 
    resultsList.put("name", person.getName()); 
    resultsList.put("surname", person.getSurname()); 
    List<Map<Strin, Object>> addressesList = new ArrayList<Map<Strin, Object>>(); 
    for(Address address: person.getAddresses()) { 
     addressesList.put("city", address.getCity()); 
     addressesList.put("street", address.getStreet()); 
     addressesList.put("type", address.getType()); 
    } 
    resultsList.put("name", person.ngetName()); 
} 

在此之後resultsList將包含您需要的結構。

+0

可以從查詢中返回一個List >。 通過按照你寫的,我從數據庫中獲取所有實體(我不想做的),並且我可能有許多數據庫查詢,每個'Person'獲取'Adress'es。 – user1137146 2012-08-15 14:58:44