How to Insert List with JPA

0

Good afternoon!

I'm doing a web service that gets a Json from the application, unencapsulates and inserts into the database. I can decode normally, the problem occurs at the time of inserting the data into the database.

I have a list inside an object and at the time of inserting it, it inserts several instead of just an object and seize the key to enter the data from the list.

For example, within the json commanded by the user, you have a list of rooms in an apartment, when you enter those rooms, it repeats everything else.

Json received:

 '{"email":"[email protected]","enderecoList":[{"bairroSetor":"Centro","cep":"877777770","cidade":"Palmas","complemento":"SN","estado":"TO","imovelList":[{"comodosList":[{"nome":"Garagem - Demoliçao de Muro"},{"nome":"Garagem - Construção de Muro"},{"nome":"Garagem - Regularização de Contrapiso"},{"nome":"Área Externa - Demoliçao de Muro"},{"nome":"Área Externa - Construção de Muro"},{"nome":"Área Externa - Regularização de Contrapiso"}],"tipo":"Casa"}],"ruaAlameda":"Rua 1"}],"horario":"Tarde","nome":"Teste","telefone":"(63) 98889-2200"}
'

Methods where I get json and I enter

     @POST
    @Path("inserir")
    @Produces({MediaType.APPLICATION_JSON})
    @Consumes({MediaType.APPLICATION_JSON})
    public void add(String content) {

        Gson g = new Gson();

        Usuario usuario = (Usuario) g.fromJson(content, Usuario.class);

        Usuario usuarioPersist = new Usuario();
        Endereco enderecoPersist = new Endereco();
        Imovel imovelPersist = new Imovel();
        Comodos comodoPersist = new Comodos();

        for (Endereco endereco : usuario.getEnderecoList()) {
            comodoPersist = new Comodos();
            for (Imovel imovel : endereco.getImovelList()) {
                for (Comodos comodo : imovel.getComodosList()) {

                    usuarioPersist.setEmail(usuario.getEmail());
                    usuarioPersist.setHorario(usuario.getHorario());
                    usuarioPersist.setNome(usuario.getNome());
                    usuarioPersist.setTelefone(usuario.getTelefone());

                    enderecoPersist.setBairroSetor(endereco.getBairroSetor());
                    enderecoPersist.setCep(endereco.getCep());
                    enderecoPersist.setCidade(endereco.getCidade());
                    enderecoPersist.setComplemento(endereco.getComplemento());
                    enderecoPersist.setEstado(endereco.getEstado());
                    enderecoPersist.setNumero(endereco.getNumero());
                    comodoPersist.setNome(comodo.getNome());
//                    comodos.add(comodoPersist);
                    imovelPersist.setTipo(imovel.getTipo());
                    enderecoPersist.setRuaAlameda(endereco.getRuaAlameda());

                    enderecoPersist.setUsuarioId(usuarioPersist);
                    imovelPersist.setEnderecoId(enderecoPersist);
                    comodoPersist.setImovelId(imovelPersist);

                    new ComodoRepository().save(comodoPersist);
                }

            }

ComodoRepository Class

public class ComodoRepository extends GenericDAO<Comodos> {

    public ComodoRepository() {
        super(Comodos.class);
    }

}

GenericDAO Class

 public abstract class GenericDAO<T extends Serializable> {

    private Class<T> aClass;

    protected GenericDAO(Class<T> aClass) {
        this.aClass = aClass;
        this.log = LogManager.getLogger(aClass.getName());;
    }

    protected EntityManager getEntityManager() {
        return JPAUtil.getInstance().getEntityManager();
    }


      public void save(T entity) {
        EntityManager manager = getEntityManager();
        manager.getTransaction().begin();
        manager.persist(entity);
        manager.getTransaction().commit();
        manager.close();
    }

Solution

I was able to get the solution by first inserting the property entity, retrieving the id and setting it on the Commodity entity to insert it separately.

 for (Endereco endereco : usuario.getEnderecoList()) {
            comodoPersist = new Comodos();
            for (Imovel imovel : endereco.getImovelList()) {
                usuarioPersist.setEmail(usuario.getEmail());
                usuarioPersist.setHorario(usuario.getHorario());
                usuarioPersist.setNome(usuario.getNome());
                usuarioPersist.setTelefone(usuario.getTelefone());

                enderecoPersist.setBairroSetor(endereco.getBairroSetor());
                enderecoPersist.setCep(endereco.getCep());
                enderecoPersist.setCidade(endereco.getCidade());
                enderecoPersist.setComplemento(endereco.getComplemento());
                enderecoPersist.setEstado(endereco.getEstado());
                enderecoPersist.setNumero(endereco.getNumero());

                imovelPersist.setTipo(imovel.getTipo());
                enderecoPersist.setRuaAlameda(endereco.getRuaAlameda());

                enderecoPersist.setUsuarioId(usuarioPersist);
                imovelPersist.setEnderecoId(enderecoPersist);

                imovelRepository.salvar(imovelPersist);
                Imovel imovelId = new ImovelRepository().findById(imovelPersist.getId());

                for (Comodos comodo : imovel.getComodosList()) {

                    comodoPersist.setNome(comodo.getNome());
                    comodoPersist.setImovelId(imovelId);
                    comodoRepository.salvar(comodoPersist);
                }

            }

        }

I also added the findById method to the GenericDAO class.

public T findById(Integer id) {
    EntityManager manager = getEntityManager();
    manager.getTransaction().begin();

    T entity = (T) manager.find(aClass, id);

    manager.getTransaction().commit();
    manager.close();

    return entity;
}
    
asked by anonymous 27.03.2017 / 21:43

1 answer

0

I had a familiar problem, in my case my object was not compressed so I put @GZIP

@POST
@GZIP @Consumes (MediaType.APPLICATION_JSON) public Response saveData (@GZIP RecievingData customer);

    
27.03.2017 / 21:50