Hibernate self relationship transforming into json breaks

Asked

Viewed 630 times

0

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

I have created a method similar to a "Tester" to popular and seek the persistent information.

But when I search for the information, in debug mode it’s as if my result is an infinite array (loop) because I have a self relationship.

It goes 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 recover this query and turn 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();

    }

}

1 answer

0


I was able to solve my problem using Google’s lib gson.
I used the Annotation:

@Exposed  

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.