Série da semana: Primeiros passos no Angular

Veja mais

Problema Jersey Web Service em relacionamento 1:n

17/06/2018

2

Estou tendo problema com o relacionamento bidirecional. Quando não há relacionamento o Postman retorna o JSON corretamente, mas quando uso o relacionamento @OneToMany vem a exceção. O @JsonIgnore não funciona, inclusive fiz teste em campos não relacionados e o JsonIgnore também não funciona.
Estou usando o EclipseLink ao invés do Hibernate.

Classe:
package model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.List;
import javax.persistence.FetchType;

/**
 *
 * @author luiz
 */
@Entity
public class Proprietario implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nome;
    private String endereco;
    @OneToMany(mappedBy = "proprietario",  fetch = FetchType.EAGER)
    @JsonIgnore
    private List<Animal> animais;

//getter e setter


Classe Animal:
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

/**
 *
 * @author luiz
 */
@Entity
public class Animal implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nome;
    private Integer idade;
    
    @ManyToOne(fetch = FetchType.EAGER)
    @JsonIgnore
    private Proprietario proprietario;

//getters e setters



Dao:
package dao;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import model.*;

/**
 *
 * @author acg
 */
@Stateless
public class ProprietarioDao {

    @PersistenceContext
    EntityManager em;

    public ProprietarioDao() {
    }
    
    public void gravar(Proprietario proprietario) {
        em.persist(proprietario);
    }

    public void gravar(Animal animal) throws Exception{
        
        if (animal.getIdade()>20) {
            throw new Exception ("Nao pode animal com mais de 20 anos");
        }
        em.persist(animal);
    }
    
    public List<Proprietario> get() {
        Query q = em.createQuery("select p from Proprietario p order by p.nome");
        return q.getResultList();
    }
}

Rest:
package service;

import dao.ProprietarioDao;
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import model.Animal;
import model.Proprietario;

/**
 *
 * @author giovannicolonese
 */
@Named
@Path("proprietario")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ProprietarioRes {

    @EJB
    ProprietarioDao daoProprietario;
@GET
    @Path("listarproprietarios")
    public List<Proprietario> getProprietarios() {
        return daoProprietario.get();
    }


Exceção:
StandardWrapperValve[service.RestApplication]: Servlet.service() for servlet service.RestApplication threw exception
java.lang.StackOverflowError
at org.eclipse.yasson.internal.serializer.DefaultSerializers.findValueSerializerProvider(DefaultSerializers.java:101)
at org.eclipse.yasson.internal.serializer.SerializerBuilder.getSupportedTypeSerializer(SerializerBuilder.java:149)
at org.eclipse.yasson.internal.serializer.SerializerBuilder.build(SerializerBuilder.java:87)
at org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:102)
at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:63)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:64)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:96)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializeItem(AbstractContainerSerializer.java:134)
at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:49)
at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:30)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:64)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:96)
at org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:103)
at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:63)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:64)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:96)
at org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:103)
at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:63)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:64)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:96)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializeItem(AbstractContainerSerializer.java:134)
at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:49)
at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:30)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:64)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:96)
at org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:103)
at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:63)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:64)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:96)
at org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:103)
at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:63)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:64)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:96)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializeItem(AbstractContainerSerializer.java:134)
at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:49)
at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:30)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:64)
at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCap
Responder

Post mais votado

20/06/2018

Encontrei a resposta. O problema era configurar o glassfish para usar o Jackson. Usei a classe abaixo para configurar.
Este é o trecho específico do código usado para forçar o glassfish a usar o Jackon:
// Add JacksonFeature.
classes.add(JacksonFeature.class);

package service;

import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.jackson.JacksonFeature;


@ApplicationPath("rest")
public class RestApplication extends Application {
    
   @Override
   public Set<Class<?>> getClasses() {
        final Set<Class<?>> classes = new HashSet<Class<?>>();

        // Add root resources.
        classes.add(ProprietarioRes.class);

        // Add JacksonFeature.
        classes.add(JacksonFeature.class);

        return classes;
    }

Achei a resposta no seguinte link:
https://stackoverflow.com/questions/18317927/force-glassfish4-to-use-jackson-instead-of-moxy
Responder