3

hope things are going well.

I am attempting to implement a @ManyToMany bidirectional mapping in Spring MVC utilizing Spring Boot, Spring Data JPA, Hibernate, Gradle, and Spring Data Rest. When I implement the mapping between my two (2) entities, Events and Tags. An Event can zero to many Tags and a Tag can be associated with zero to many Events. I am in fact able to successfully save POJOs to the hibernate session, including a HashSet<>() through a setter of the mapped entities. However, as soon as I as soon as I attempt to query a list of the POJOs through a CrudRepository method such as .findAll(), it immediately blows. Looking at the console output, it looks like Hibernate is attempting to append the other object hundred+ times. As I'm using @RestController for the the list action (.findAll()), when I navigate the RESTful endpoint, instead of showing just the two JSON objects, it shows a massive unclosed appended mess of JSON fragments. The console output is also indicating jackson databind may be having issues with serializing the .findAll() results that Hibernate is outputting.

Any help would be greatly appreciated. The biggest confusion for me is why Hibernate would attempt to append the result string so so many times. Is this perhaps an issue with:

  1. @ManyToMany mapping configuration? Needs @JoinColumns on Tag entity?
  2. fetch = FetchType.EAGER?
  3. Lacking/Excessive GETTER/SETTER? Remove/add GETTER/SETTER from either Event or Tag entities?
  4. Spring Boot and/or Gradle? Any other example I can find on the interwebs is utilizing Maven.
  5. Dependencies? spring-starter-boot-starter-data-jpa vs spring-data-jpa?
  6. Constructors? (Event.java does not have parameter constructor for tags)
  7. HashSet<>() property type for events and/or tags?

build.gradle

dependencies {
    compile("org.springframework.boot:spring-boot-starter-data-rest")
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("org.hibernate:hibernate-validator")
    compile("org.apache.tomcat.embed:tomcat-embed-el")
    compile("com.h2database:h2")
}

Event.java

package event.model;

import org.hibernate.validator.constraints.Email;
import org.springframework.format.annotation.DateTimeFormat;

import javax.persistence.*;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.*;

@Entity
@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"title", "date"})})
public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @NotNull
    @Size(min = 2, max = 55)
    private String title;

    // .. some additional private variables

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "events_tags",
            joinColumns=@JoinColumn(name = "event_id"),
            inverseJoinColumns = @JoinColumn(name="tag_id")
    )
    private Set<Tag> tags = new HashSet<>();

    public Event() {
    }

    public Event(String title, String description, Date date, String organizer, String email, String location) {
        this.title = title;
        this.description = description;
        this.date = date;
        this.organizer = organizer;
        this.email = email;
        this.location = location;
    }

    public long getId() {
        return id;
    }

    // .. GETTERS and SETTERS for other properties

    public Set<Tag> getTags(){
        return tags;
    }

    public void setTags(Set<Tag> tags){
        this.tags = tags;
    }

    // @Overide toString() method
}

Tag.java

package event.model;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.*;

@Entity
public class Tag {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @NotNull
    @Size(min = 3, max = 255)
    private String title;

    @ManyToMany(mappedBy = "tags", fetch = FetchType.EAGER)
    private Set<Event> events = new HashSet<>();

    public Tag() {
    }

    public Tag(String title) {
        this.title = title;
    }

    public long getId() {
        return id;
    }

    // .. GETTERS AND SETTERS

    public Set<Event> getEvents() {
        return events;
    }

    public void setEvents(Set<Event> events){
        this.events = events;
    }

    // @Override toString() method

}

Application.java

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    EventRepository eventRepository;

    @Autowired
    TagRepository tagRepository;

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... strings) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy HH:mm a");
        String[] dateStrings = {"07-25-2015 12:00 PM", "08-25-2015 12:00 PM"};

        Date date1 = formatter.parse(dateStrings[0]);
        Date date2 = formatter.parse(dateStrings[1]);

        Event event1 = eventRepository.save(new Event("Bacon Day", "This day is about bacon. I just need so much bacon all the time", date1, "John Smith", "[email protected]", "W523"));
        Event event2 = eventRepository.save(new Event("Salad Day", "This day is about salad. I just need so much salad all the time", date2, "Jane Smith", "[email protected]", "N423"));

        Tag tag1 = tagRepository.save(new Tag("Savory"));
        Tag tag2 = tagRepository.save(new Tag("Vegetarian"));

        event1.getTags().add(tag1);
        event1.getTags().add(tag2);
        event1 = eventRepository.save(event1);
        System.out.println(event1);
        System.out.println(eventRepository.findAll());
    }
}

Console error output

Hibernate: select events0_.tag_id as tag_id2_2_0_, events0_.event_id as event_id1_1_0_, event1_.id as id1_0_1_, event1_.date as date2_0_1_, event1_.description as descript3_0_1_, event1_.email as email4_0_1_, event1_.location as location5_0_1_, event1_.organizer as organize6_0_1_, event1_.title as title7_0_1_ from events_tags events0_ inner join event event1_ on events0_.event_id=event1_.id where events0_.tag_id=?
2015-07-13 18:35:28.084 ERROR 4088 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler processing failed; nested exception is java.lang.StackOverflowError] with root cause

java.lang.StackOverflowError: null
    at java.util.Date.getYear(Date.java:651)
    at java.sql.Timestamp.toString(Timestamp.java:279)
    at java.lang.String.valueOf(String.java:2982)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at event.model.Event.toString(Event.java:128)
    at java.lang.String.valueOf(String.java:2982)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at java.util.AbstractCollection.toString(AbstractCollection.java:462)
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:317)
    at java.lang.String.valueOf(String.java:2982)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at event.model.Tag.toString(Tag.java:51)
    at java.lang.String.valueOf(String.java:2982)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at java.util.AbstractCollection.toString(AbstractCollection.java:462)
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:317)
    at java.lang.String.valueOf(String.java:2982)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at event.model.Event.toString(Event.java:128)
    at java.lang.String.valueOf(String.java:2982)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at java.util.AbstractCollection.toString(AbstractCollection.java:462)
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:317)
    at java.lang.String.valueOf(String.java:2982)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at event.model.Tag.toString(Tag.java:51)
    at java.lang.String.valueOf(String.java:2982)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at java.util.AbstractCollection.toString(AbstractCollection.java:462)
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:317)
    at java.lang.String.valueOf(String.java:2982)
    at java.lang.StringBuilder.append(StringBuilder.java:131)

That continues for hundreds more lines.

2 Answers 2

3

Try using @JsonIgnore in the child class on parents collection. It is trying to serialize recursively.

Follow this link for other ways to handle this.

2
  • I attempted to place @JsonIgnore annotation on various entity properties including the public Set<Event> getEvents() and private Set<Event> events = new HashSet<>();. It's still attempting to string build recursively. Maybe this is something the CrudRepository is not able to handle, perhaps I'd need just JpaRepository? Commented Jul 14, 2015 at 2:48
  • I have not tried either of them, but it seems the JpaRepository is a subclass of CrudRepository so you can try with that once.
    – RP-
    Commented Jul 14, 2015 at 5:17
1

I had a similar problem and solved it using @JsonBackReference:

@ManyToMany(mappedBy = "tags")
@JsonBackReference
private Set<Event> events = new HashSet<>();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.