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

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

问题描述

我将 Ebean 与 Play 2 框架一起使用,并获得了两个模型:用户模型和书籍模型.用户模型与书籍模型以 OneToMany 关系连接.所以每个用户都可以有很多书,也可以根本没有书.书本模型本身也有属性.现在我想在用户模型中创建一个查询,它只返回拥有具有某些属性的书籍的用户.例如: 一个属性可能是条件,如新的或使用的.现在给我所有拥有新书的用户.是否可以使用 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天全站免登陆