OneToMany关系的Ebean查询

时间:2014-01-18 09:50:20

标签: java playframework playframework-2.0 ebean

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

2 个答案:

答案 0 :(得分: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);

  [...]
}

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

  [...]
}

然后你可以进行搜索:

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

答案 1 :(得分:0)

List<User> users = User.find.select("*")
                        .fetch("books")
                        .where()
                        .eq("t1.condition", "new")
                        .findList();

对我来说,它仅在我使用“t1。”时才有效,我使用的是Postgres DB。生成的查询对t1有意义。