ManyToMany getter always null in Play Framework

64 views
Skip to first unread message

David Titarenco

unread,
Nov 3, 2011, 10:19:47 PM11/3/11
to play-fr...@googlegroups.com
I'm new to Hibernate/JPA and the Play Framework, I'm trying to build a relatively simple relationship between a `User` and a `Team`: a user can be on many teams and a team contains many users. This relationship is stored in the table `roster` which looks something like:

     ------------------
    |user_id | team_id |
    |------- | ------  |
    |        |         |
     ------------------

Here's the `User` model:

    @Entity
    public class User extends Model {
        @ElementCollection
        private Set<Team> teams = new HashSet();
    
            // .. other stuff
   
        @ManyToMany(mappedBy="players", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
        public Set<Team> getTeams() {
            return teams;
        }
   
            // .. other stuff
    }


And here's the `Team` model:

    @Entity
    public class Team extends Model {
   
        @ElementCollection
        private Set<User> players = new HashSet();

            // .. other stuff
   
        @ManyToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
        @JoinTable(name="roster")
        public Set<User> getPlayers() {
            return players;
        }

            // .. other stuff
    }

But whenever I try to make a new team: and add a couple of players (i.e.):

    team.getPlayers().add(getUser()); // utility function that gets the logged in user
    // or
    team.getPlayers().add((User)User.find("byId", someId).fetch());

`team.getPlayers()` is always null and I fail with a `NullPointerException occured : null ` error. I have no idea what I'm doing wrong, and every piece of documentation I look at is not very helpful.

Jorge Mota

unread,
Nov 7, 2011, 12:12:24 AM11/7/11
to play-fr...@googlegroups.com
try to do the get as it:

public Set<User> getPlayers() {
if (players==null){
players= new Set<User>();
}
            return players;
        }

-------
>++++++++++
[>+++++++>+++++++++++>+++>++++++++++>++++++++>+++++++
+++<<<<<<-]>++++.>+.+++.>>+++.--.<++.>>---.<<<---.+++++.>>>>---.




--
You received this message because you are subscribed to the Google Groups "play-framework" group.
To view this discussion on the web visit https://groups.google.com/d/msg/play-framework/-/e3rYFdpnVkMJ.
To post to this group, send email to play-fr...@googlegroups.com.
To unsubscribe from this group, send email to play-framewor...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/play-framework?hl=en.

Reply all
Reply to author
Forward
0 new messages