Search code examples
javahibernatedozer

How to map a set o Integer to a set of Objects with Dozer?


I have a set of integers that I get from db with hibernate

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "artigo_idioma", joinColumns=@JoinColumn(name="id_artigo"))
@Column(name = "id_idioma")
@Fetch(FetchMode.JOIN)
private Set<Integer> idiomas;

I can't get the whole object in the db because of a perfomance issue, and neither use lazy fetching. But I would like to map all of the Ids to the real POJO using Dozer, so that when I need the whole object I can get it by the Id I already have.


Solution

  • I solved it implementing a custom dozer for the Set

    public class SetIdIdiomaToSetIdioma extends DozerConverter<Set, Set>{
    
    
    public SetIdIdiomaToSetIdioma() {
        super(Set.class, Set.class);
    }
    
    @Override
    public Set<Idioma> convertFrom(Set ids, Set idiomas) {
        if(ids != null && ids.size() > 0){
            idiomas = new HashSet<Idioma>();
            for (Object object : ids) {
                if(object.getClass().equals(Integer.class)){
                    Integer id = (Integer) object;
                    if(id != null){
                        Idioma idioma = new Idioma();
                        idioma.setIdIdioma(id);
                        idiomas.add(idioma);
                    }
                }
            }
        }
    
        return idiomas;
    }
    
    @Override
    public Set<Integer> convertTo(Set idiomas, Set ids) {
        if(idiomas != null && idiomas.size() > 0){
            ids = new HashSet<Integer>();
            for (Object object : idiomas) {
                Idioma idioma = (Idioma) object;
                if(idioma != null && idioma.getIdIdioma() != null)
                    ids.add(idioma.getIdIdioma());
            }
        }
        return ids;
    }
    
    
    }
    

    Once it's done I have a set of the object I want and, if I need, I can search in db provinding the id for the aditional data.