错误经由使用RawSql ebean执行MySQL查询(Error executing MySQL

2019-09-29 12:32发布

在玩游戏! 2.x的应用程序,我想一个简单的查询发送到使用ebean一个MySQL服务器。

我完整的类如下所示:

public static List<Venue> search(String query) {
    List<Venue> matches = new ArrayList<Venue>();
    try {
        String q = query.replace(" ", "");

        String sql =    "SELECT  v.id, c.company, c.postcode \n" +
                        "FROM    venue v \n" +
                        "JOIN    contact c ON (c.id = v.id) \n" +
                        "WHERE   REPLACE(c.postcode, ' ', '') LIKE '%" + q + "%' \n" +
                        "    OR  c.company LIKE '%" + q + "%'";

        RawSql rawSql = RawSqlBuilder.unparsed(sql)
            .columnMapping("v.id", "id")
            .columnMapping("c.company", "contact.company")
            .columnMapping("c.postcode", "contact.postcode")
            .create();

        Query<Venue> eQ = Ebean.find(Venue.class);

        eQ.setRawSql(rawSql);

        matches = eQ.findList();
    }
    catch (Exception e) {
        Utils.eHandler("Venue.search(" + query + ")", e);
    }
    finally {
        return matches;
    }
}

但是,在执行行...

matches = eQ.findList();

在以下的错误,这似乎是一个MySQL错误..results(?):

Query threw SQLException:Column Index out of range, 0 < 1.
Bind values:[]
Query was:
SELECT  v.id, c.company, c.postcode
FROM    venue v
JOIN    contact c ON (c.id = v.id)
WHERE   REPLACE(c.postcode, ' ', '') LIKE '%sw3%'
        OR  c.company LIKE '%sw3%'

查询本身是好的,比如我可以从错误信息复制版本,将其粘贴到MySQL工作台,它执行没有问题。

请注意,我用RawSql因为我需要有超过2“或”条款,而据我所知,这是做到这一点的唯一途径。

任何人都可以帮忙吗?

谢谢!

Answer 1:

发现问题(或溶液,至少)。 “接触”是“地点”的子对象,不能映射不指定联系人标识符联系字段(如“contact.company”)。 所以,下面的代码,添加了对contact.id适当的元素,工作原理:

String sql =    "SELECT  v.id, c.id, c.company, c.postcode " +
                "FROM    venue v " +
                "JOIN    contact c ON (c.id = v.id) " +
                "WHERE   REPLACE(c.postcode, ' ', '') LIKE '%" + q + "%' " +
                "    OR  c.company LIKE '%" + q + "%'";

RawSql rawSql = RawSqlBuilder.unparsed(sql)
    .columnMapping("v.id", "id")
    .columnMapping("c.id", "contact.id")
    .columnMapping("c.company", "contact.company")
    .columnMapping("c.postcode", "contact.postcode")
    .create();

甚至比这更好的,因为程序只是返回在查询匹配“地点”对象的列表,它甚至没有必要包含附加字段,所以我真正需要的是下面的(这也适用):

String sql =    "SELECT  v.id " +
                "FROM    venue v " +
                "JOIN    contact c ON (c.id = v.id) " +
                "WHERE   REPLACE(c.postcode, ' ', '') LIKE '%" + q + "%' " +
                "    OR  c.company LIKE '%" + q + "%'";

RawSql rawSql = RawSqlBuilder.unparsed(sql)
    .columnMapping("v.id", "id")
    .create();


文章来源: Error executing MySQL query via ebean using RawSql