1

在剧中!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 错误(?):

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 Workbench 中,它执行没有问题。

请注意,我使用的是 RawSql,因为我需要有超过 2 个“OR”子句,据我所知,这是唯一的方法。

任何人都可以帮忙吗?

谢谢!

4

1 回答 1

2

找到问题(或至少是解决方案)。由于“Contact”是“Venue”的子对象,如果不指定 Contact 标识符,您将无法映射到 Contact 字段(例如“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();
于 2012-12-21T14:10:47.333 回答