1
votes

I have three tables: users(id, name, login, password), roles(id, name), user_roles(id, user_id, role_id)

This is my code

@Entity
@Table(name = "users")
public class User extends Model {
    @Id
    public Long id;

    public String name;

    public String login;

    public String password;

    @ManyToMany
    @JoinTable(
            name = "user_roles",
            joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")
    )
    public Set<Role> roles;

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

@Entity
@Table(name = "roles")
public class Role extends Model {
    @Id
    public Long id;

    public String name;

    @ManyToMany(mappedBy = "roles")
    public List<User> users;

    public static Finder<Integer, Role> find = new Finder<>(Role.class);
}

I want to display all users with roles, example: {"id":1, "name":"My Name", "login":"My Login", "password":"My Password", roles: [{"name":"ADMIN"}, {"name":"USER"}]} How can I do this? I'm new in Ebean and ORM. Thanks for any help.

Update

public Result all() {
    List<User> users = User.find.all();
    return ok(toJson(users));
}

But now I getting stackoverflow error infinite recursion.

1
I solved it the answer in this question from user Kurt BourbakiEvgeniy

1 Answers

0
votes

Make users.role = null and then return Json