linsenfips linsenfips - 1 year ago 135
Java Question

Ebean Query by OneToMany Relationship

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?

Answer Source

Say you have the following models:

public class User extends Model {
  @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);



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

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

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


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


Then you can do a search like:

List<User> users ="*")
                            .eq("books.condition", "new")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download