定制的DTO和重复 [英] customized DTO and repeatition
问题描述
我在mysql
dababase中有两个表country
和city
,并在hibenrate/jpa
中映射为One-to-Many
关系.
我这样查询
select new MyDTO(country.id,country.name, city.id, city.name) from country
inner join city on city.fk_country = country.id
where .....
我使用自定义的DTO
的原因是对象城市包含其他字段(城市属性),并且我不想检索它们,我只需要ID和名称.
问题是我的结果中有重复的国家/地区
1,france,1,paris
1,france,2,marseille
1,france,3,lion
....
那么我该如何使自己像冬眠般将城市归入集合或其他内容中.
我未使用休眠映射(实体Country
),原因是在休眠/jpa中我们无法指定要在集合中检索的字段.
我的国家实体
@Entity
@Table(name = "country", catalog = "ao")
public class Country implements java.io.Serializable {
private Integer id;
private String name;
private String .... ;
private Integer .... ;
private Boolean .... ;
....
....
private Set<City> cities = new HashSet<City>(0);
我的城市实体
@Entity
@Table(name = "city", catalog = "ao")
public class City implements java.io.Serializable {
private Integer id;
private String name;
//other properties
private String ...;
private String ...;
private Long ...;
...
...
...
private Country country;
类似于 My City entity
Like this ansnwer from @mohit Create additional classes for country and city. Transform the flat structure to nested structure of country and cities as shown below: The final Collection of Country will result is the desired JSON. 这篇关于定制的DTO和重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!@Entity
@Table(name = "city", catalog = "ao")
public class City implements java.io.Serializable {
private Integer id;
private String name;
//other properties
private String ...;
private String ...;
private Long ...;
...
...
...
private Country country;
public class Country {
Integer idLvl1;
String nameLvl1;
public Country(Integer idLvl1, String nameLvl1) {
}
List<City> cities;
}
public class City {
Integer idLvl2;
String nameLvl2;
public City(Integer idLvl2, String nameLvl2) {
}
}
public class MyDTOConverter {
public static Collection<Country> covert(List<MyDTO> dtos){
Map<Integer, Country> countries = new LinkedHashMap<Integer, Country>();
for (MyDTO myDTO : dtos) {
//First adding the country if it doesn't exist
if (!countries.containsKey(myDTO.idLvl1)){
countries.put(myDTO.idLvl1, new Country(myDTO.idLvl1, myDTO.nameLvl1));
}
//Adding city in the existing country.
countries.get(myDTO.idLvl1).cities.add(new City(myDTO.idLvl2, myDTO.nameLvl2));
}
return countries.values();
}
}