通过一对多关系进行Ebean查询 [英] Ebean Query by OneToMany Relationship

查看:263
本文介绍了通过一对多关系进行Ebean查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Ebean与Play 2 Framework结合使用,并得到了两种模型:用户模型和书本模型.用户模型与书籍模型以一对多关系连接.因此,每个用户可以拥有很多书,甚至根本没有书.书籍模型本身也具有属性.现在,我想在用户模型中创建一个查询,该查询仅返回拥有书籍具有某些属性的用户.例如:一个属性可能是条件,例如new或used.现在,给我所有拥有新状态图书的用户. 是否可以使用Ebean方法创建这样的查询?还是我必须使用原始SQL?

I'm using Ebean with the Play 2 Framework and got two models: a user model and a book model. The user model is connected with the book model in a OneToMany Relationship. So every user can have many books or no book at all. The book model itself has properties too. Now I want to create a query in the user model, which returns only users, who have books with certain properties. For example: One property might be condition, like new or used. Now give me all users which have books in new condition. Is it possible to create such a query with the Ebean methods? Or do I have to use raw SQL?

推荐答案

假设您具有以下模型:

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

  [...]
}

然后,您可以进行如下搜索:

Then you can do a search like:

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

这篇关于通过一对多关系进行Ebean查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆