Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StackoverflowError JPA in OneToMany relationship

So I have 2 classes: Game and User. User can play 1 or more games so it'a a OneToMany relationship between them. Here are the classes.

And I try to make the relationship bidirectional between classes.

Game:

@Entity
public class Game {
    @Id
    @Column(name = "GAME_NUMBER")
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long gameNumber;

    private int playerScore;
    private int NPCScore;
    private Date datetime;

    @ManyToOne
    @JoinColumn(name="USER_ID")
    private User user;

    public Game() {}

    public Game(int playerScore, int nPCScore, Date datetime) {
        super();
        this.playerScore = playerScore;
        this.NPCScore = nPCScore;
        this.datetime = datetime;
    }

    public User getUser() {
        return user;
    }
} + getters & setters for attributes

User:

@Entity
public class User {
    @Id
    @Column(name = "USER_ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long userId;

    private String username;
    private String password;

    @OneToMany(mappedBy="user",cascade=CascadeType.ALL)
    private List<Game> games;

    @ElementCollection
    private List<Date> startSessions;

    public User() {}

    public User(String username, String password, List<Game> games, List<Date> startSessions) {
        super();
        this.username = username;
        this.password = password;
        this.games = games;
        this.startSessions = startSessions;
    }
}

So when the user plays a new game the below method finds the user in database(hsqldb) and we add the new game to the List. Because the relationship is bidirectional I set the user to each Game played ...so this is what causing the problem. Can I fix in some other way?

@RequestMapping(value = "/game/play", method = RequestMethod.POST)
@ResponseBody
public User indexRequestPlay(@RequestParam String username, @RequestParam String password) {

    User user = userRepository.findByUsernameAndPassword(username, password);

    Random random = new Random();
    int userScore = random.nextInt(5) + 1;
    int npcScore = random.nextInt(5) + 1;
    Date date = new Date();

    List<Date> startSessions = user.getStartSessions();
    startSessions.add(date);
    user.setStartSessions(startSessions);

    Game game = new Game(userScore, npcScore, date);
    game.setUser(user);
    List<Game> games = new ArrayList<Game>();
    games.addAll(user.getGames());
    games.add(game);
    user.setGames(games);

    userRepository.save(user);
    return user;
}

I am receiving this errors:

java.lang.IllegalStateException: Cannot call sendError() after the response has been committed

and stackoverflowerror

like image 574
Rares Avatar asked Jun 11 '17 09:06

Rares


People also ask

How do you write one to many relationship in JPA?

Define Data Model for JPA One to Many mapping – @Entity annotation indicates that the class is a persistent Java class. – @Table annotation provides the table that maps this entity. – @Id annotation is for the primary key. – @GeneratedValue annotation is used to define generation strategy for the primary key.

Can a JPA entity have multiple OneToMany associations?

You can have multiple one-to-many associations, as long as only one is EAGER. But, even if you can use Set instead of List to bypass this MultipleBagFetchException , it's not a good thing to do because you'll end up with a Cartesian Product.

What is one to many relationship in Spring JPA?

A one-to-many relationship between two entities is defined using the @OneToMany annotation in Spring Data JPA. It declares the mappedBy element to indicate the entity that owns the bidirectional relationship.

What is Java Lang StackOverflowError?

lang. StackOverflowError is a runtime error which points to serious problems that cannot be caught by an application. The java. lang. StackOverflowError indicates that the application stack is exhausted and is usually caused by deep or infinite recursion.


1 Answers

I figured it out that the JSON was the problem..... I got Infinite Recursion with the JSON. I added this @JsonManagedReference and @JsonBackReference. and fixed the problem. You can check the full answer here. Thx!

https://stackoverflow.com/a/18288939/7947794

like image 132
Rares Avatar answered Nov 03 '22 21:11

Rares