具有桥表的Ebean ManyToMany查找所有查询

时间:2016-06-08 14:49:06

标签: java playframework orm ebean

我有三个表:用户(id,名称,登录名,密码),角色(id,名称),user_roles(id,user_id,role_id)

这是我的代码

@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);
}

我希望显示所有具有角色的用户,例如:{&#34; id&#34;:1,&#34; name&#34;:&#34;我的名字&#34;,&#34;登录& #34;:&#34;我的登录&#34;,&#34;密码&#34;:&#34;我的密码&#34;,角色:[{&#34; name&#34;:&#34; ADMIN&#34;},{&#34; name&#34;:&#34; USER&#34;}]} 我怎样才能做到这一点?我是Ebean和ORM的新人。谢谢你的帮助。

更新

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

但现在我得到stackoverflow错误无限递归。

1 个答案:

答案 0 :(得分:0)

制作users.role = null,然后返回Json