Alex Povar
Alex Povar

Reputation: 4960

Ebean Play framework 2 many-to-many association loading

a bit of troubles from Play Framework 2 here. There are two classes:

@Entity
public class User extends Domain {

    @Id
    public Long id;
    public String name;
    public String surname;
    public String phoneNumber;

    @Lob
    public String comment;

    @ManyToMany
    public Set<Band> groups = new HashSet();
}

@Entity
public class Band extends Domain {

    @Id
    public Long id;

    public String name;

    @Lob
    public String comment;

    @ManyToMany(mappedBy="groups")
    public Set<User> users = new HashSet();
}

And the problem with accessing User.groups. Doing

System.out.println(user.groups);

return the following:

BeanSet deferred

exactly like in this question. So the question is should I do something to make it loaded?

But running this code makes everything as expected.

Band.find.all();
System.out.println(user.groups);

What the reason of such behaviour?

P.S. Domain class is Model inheritor which keeps few static methods.

Upvotes: 2

Views: 4356

Answers (1)

biesior
biesior

Reputation: 55798

It's MM relation so user.groups is Set<Band>, not just Band type. You need to iterate trough it...

First you need create a Finder in your classes (if you hadn't yet):

User:

public static Finder<Long, User> find 
        = new Finder<Long, User>(Long.class, User.class);

Band:

public static Finder<Long, Band> find 
        = new Finder<Long, Band>(Long.class, Band.class);

Next you need to fetch and iterate the allUsers as List<User> AND inside iterate the Set<Band> (available as user.groups):

List<User> allUsers = User.find.all();
for (User user : allUsers) {
    Logger.info("User's name is " + user.name);
    for (Band group : user.groups) {
        Logger.info(user.name + " in group " + group.name);
    }
}

Of course when you'll find single Band ie. with Band.find.byId(1L) you don't need to iterate it.

Don't forget to import the Logger:

import play.Logger;

It's better than System.out.println()

Upvotes: 3

Related Questions