Hibernate auto relationship turning into json break

0

I'm using Hibernate to persist the objects in an embedded HSQLDB file.

I've created a similar method from a "tester" to popular and fetch the persisted information.

But when I look for the informations, in debug mode it's like my result is an infinite array (in loop) because I have an auto relationship.

It looks something like this: Product (instance1 of product)
   - > ParentProduct (instance2 of product)
      - > ChildProduct (this guy is the same as instance 1)
And when I try to retrieve this query and turn it into a json the code breaks with the error below:

com.google.gson.stream.JsonWriter.beforeName(JsonWriter.java:618)
    com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:401)
    com.google.gson.stream.JsonWriter.value(JsonWriter.java:527)
    com.google.gson.internal.bind.TypeAdapters$11.write(TypeAdapters.java:310)
    com.google.gson.internal.bind.TypeAdapters$11.write(TypeAdapters.java:295)
    com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:125)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:243)
    com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:976)

Follow the source:

package com.thalesgomes.ws.rest.classes;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.*;

@Entity
@Table(name="PRODUCT")
public class Product {

    @Id
    @GeneratedValue
    @Column(name="product_id")
    private Long id;

    @ManyToOne(cascade= {CascadeType.ALL})
    @JoinColumn(name="parent_id")
    private Product parent;

    private String name;

    private String description;

    @OneToMany(mappedBy="parent",cascade={CascadeType.ALL})
    private List<Product> children;

    @OneToMany(mappedBy="product",cascade={CascadeType.ALL})
    private List<Image> images;



    //Getters and Setters

}

And here:

package com.thalesgomes.ws.rest.JPA;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.google.gson.Gson;
import com.thalesgomes.ws.rest.classes.Image;
import com.thalesgomes.ws.rest.classes.Product;

public class ProductJPA {

    public static void main(String[] args) {
        populateDatabase();
        getProducts();

    }

    private static void getProducts() {
        // TODO Auto-generated method stub
        EntityManager em = getManager();
        em.getTransaction().begin();
        List<Product> products  = em.createQuery("from Product", Product.class).getResultList();
        Gson gson = new Gson();
        String json = gson.toJson(products);
        System.out.println(json);
    }

    public static EntityManager getManager() {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("Persistence");
        return factory.createEntityManager();
    }

    public static void populateDatabase() {

        List<Image> images = new ArrayList<Image>();
        Image img1 = new Image();
        Image img2 = new Image();

        Product parent = new Product();
        parent.setDescription("descriptionParent");
        parent.setName("nameParent");
        parent.setParent(null);

        Product child1 = new Product();


        img1.setProduct(parent);
        img1.setType("jpeg");
        images.add(img1);

        child1.setName("name1");
        child1.setDescription("description1");
        child1.setParent(parent);
        child1.setImages(images);

        Product child2 = new Product();
        img2.setProduct(child2);
        img2.setType("jpeg");
        images.add(img2);
        child2.setName("name2");
        child2.setDescription("description2");
        child2.setParent(parent);
        child2.setImages(images);





        EntityManager manager = getManager();
        manager.getTransaction().begin();
        try {
            manager.persist(img1);
            manager.persist(img2);
            manager.persist(parent);
            manager.persist(child1);
            manager.persist(child2);

        } catch (Exception e) {
            manager.getTransaction().rollback();
        }
        manager.getTransaction().commit();
        System.out.println("Commit done.");
        manager.close();

    }

}
    
asked by anonymous 10.07.2017 / 14:25

1 answer

0

I was able to solve my problem using google's lib gson. I used the annotation:

@Exposed  

In the child entities, making the child not have visibility of the father, but the father has the child. The same is valid for the image, where the Product should have visibility of the Image, but the image did not need to have visibility of the Product.

    
12.07.2017 / 22:03