【问题标题】:ebean query with subquery带有子查询的 ebean 查询
【发布时间】:2013-06-12 15:59:35
【问题描述】:

我正在尝试使用 EBean,相当于

select * from myTable1 where id not in (select id2 from myTable2) ;

我没有在 table2 对象中引用 table1 对象,反之亦然。 有人知道如何使用 EBean 吗?

目前我只有:

List<MyTable1> myResult = MyTable1.find.where().eq("id","1" ).findList();

谢谢。

C.C.

【问题讨论】:

    标签: sql ebean


    【解决方案1】:

    显然,自 2009 年以来,使用此错误报告中给出的示例就可以做到这一点:

    http://www.avaje.org/bugdetail-92.html

    示例:

    Query<Product> subQuery =   
        Ebean.createQuery(Product.class)  
            .select("sku")  
            .where().idEq(4).query();  
    
    List<MinCustomer> list = Ebean.find(MinCustomer.class)  
        .where().in("name", subQuery)  
        .findList(); 
    

    但是:

    我无法使它工作,因为生成的 SQL 无效。似乎是由于在 Ebean 的场景后面发生了字符串替换,其中(至少对我而言)子查询中的表名丢失了。

    我希望它与我的主查询有关,包括对我的子查询“正在选择”的表的引用。

    从示例中转出有效的 SQL:

    select c.id, c.name, c.notes   
    from o_customer c   
    where  (c.name) in (select p.sku  from o_product p  where p.id = ?  )  
    

    ...在我的情况下进入这个无效的 SQL:

    select t0.id as c0, ... t0.location_id as c8
    from myRecordClass t0
    where  (t0.location_id) in (
        select t0.id
        from t0.location_id t0    # should be: from location t0
        where t0.customer_id = ?
        )  and t0.creation > ?  
    order by t0.creation desc
    

    解决方法:

    使用 https://stackoverflow.com/a/27431625/190599 中的 RawSql 方法 - 此处为示例:

    String sql = "select b.id, b.location_id ... " +
            "from myRecordClass b " +
            "where location_id in (" +
                "select id " +
                "from location " +
                "where customer_id = " + user.getCustomer().getId() +
            ") " +
            "order by creation desc limit 10";
    
    RawSql rawSql = RawSqlBuilder
            .parse(sql)
            .columnMapping("b.id", "id")
            .columnMapping("b.location_id", "location.id")
            ....
            .create();
    
    Query<MyRecordClass> query = Ebean.find(MyRecordClass.class);
    query.setRawSql(rawSql);
    final List<MyRecordClass> list = query.findList();
    

    【讨论】:

      【解决方案2】:

      我几乎不相信RawSql 是实现这种查询的最快方法,它允许您返回映射对象列表。

      也可以使用SqlQuery(在Reference guide (PDF) 中描述)来获取SqlRows 的列表 - 这样您就可以找到所需的数据而无需任何映射。

      【讨论】:

      • 谢谢。我实际上找到了一种使用 EBean 的方法,而不是使用 rawsql。不过还是谢谢。
      • RawSql 也来自 Ebeans API :) 使用它并没有什么坏处。
      • @CC 你是怎么最终直接在 ebean 中做的?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      相关资源
      最近更新 更多