Ebean Query by OneToMany Relationship

前端 未结 2 427
挽巷
挽巷 2021-01-03 02:14

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

相关标签:
2条回答
  • 2021-01-03 02:43

    Say you have the following models:

    @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);
    
      [...]
    }
    

    and

    @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();
    
    0 讨论(0)
  • 2021-01-03 02:58
    List<User> users = User.find.select("*")
                            .fetch("books")
                            .where()
                            .eq("t1.condition", "new")
                            .findList();
    

    For me, it works only when I use "t1.", I am using Postgres DB. The generated query makes sense with t1.

    0 讨论(0)
提交回复
热议问题