【问题标题】:Ebean Query by OneToMany Relationship通过 OneToMany 关系查询 Ebean
【发布时间】:2014-01-18 09:50:20
【问题描述】:

我将 Ebean 与 Play 2 框架一起使用,并获得了两个模型:用户模型和书籍模型。用户模型与图书模型以 OneToMany 关系连接。因此,每个用户都可以拥有很多书或根本没有书。书本模型本身也有属性。现在我想在用户模型中创建一个查询,它只返回具有某些属性的书籍的用户。例如:一个属性可能是条件,如新的或使用的。现在给我所有拥有新书的用户。 是否可以使用 Ebean 方法创建这样的查询?还是我必须使用原始 SQL?

【问题讨论】:

    标签: java playframework playframework-2.0 ebean


    【解决方案1】:

    假设你有以下模型:

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

    【讨论】:

    • 非常感谢!完美运行。一个后续问题:是否可以轻松地按用户拥有的书籍数量排序?
    • 我相信你可以通过公式注释做到这一点。就像使用 @Formula(select = "(SELECT COUNT(*) FROM books WHERE book_owner_index = ${ta}.index)") 向您的 User 模型添加一个 int 字段,然后您可以按该字段订购。但这是未经测试的代码。有关详细信息,请参阅here
    • 和你说的一模一样。公式注释可以解决问题。再次感谢!
    • 旧答案,但这些模型的 SQL 看起来如何?带或不带“user_book”表(包含外键用户和书籍表)
    • 两个表的列名在 JPA 注释中给出。不需要额外的表来映射多对一关系,因为每本书只能有一个所有者,因此 book_owner_index 是 book 表的一列。
    【解决方案2】:
    List<User> users = User.find.select("*")
                            .fetch("books")
                            .where()
                            .eq("t1.condition", "new")
                            .findList();
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多