定制的DTO和重复 [英] customized DTO and repeatition

查看:109
本文介绍了定制的DTO和重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mysql dababase中有两个表countrycity,并在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

@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;

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:

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();
    }

}

The final Collection of Country will result is the desired JSON.

这篇关于定制的DTO和重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆