OneToMany关系的Ebean查询

lin*_*ips 5 java playframework ebean playframework-2.0

我正在使用Ebean和Play 2 Framework,并获得了两个模型:用户模型和书籍模型.用户模型与OneToMany关系中的书籍模型相关联.因此,每个用户都可以拥有许多书籍或根本没有书籍.书籍模型本身也有属性.现在,我想在用户模型中创建一个查询,该查询仅返回具有某些属性的书籍的用户.例如:一个属性可能是条件,如new或used.现在给我所有拥有新条件书籍的用户.是否可以使用Ebean方法创建这样的查询?或者我必须使用原始SQL?

t0m*_*ppa 11

假设您有以下型号:

@Entity
public class User extends Model {
  @Id
  @Column(name = "user_index")
  private int id;

  @Column(name = "user_first_name")
  private String firstName;

  [...]

  @OneToMany(mappedBy = "book_owner_index")
  private List<Book> books;

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

  [...]
}
Run Code Online (Sandbox Code Playgroud)

@Entity
public class Book extends Model {
  @Id
  @Column(name = "book_index")
  private int id;

  @Column(name = "book_name")
  private String name;

  @Column(name = "book_condition")
  private String condition;

  [...]

  @ManyToOne
  @JoinColumn(name = "book_owner_index", referencedColumnName = "user_index")
  private User owner;

  [...]
}
Run Code Online (Sandbox Code Playgroud)

然后你可以进行如下搜索:

List<User> users = User.find.select("*")
                            .fetch("books")
                            .where()
                            .eq("books.condition", "new")
                            .findList();
Run Code Online (Sandbox Code Playgroud)