0

我正在尝试使用带有查询的命名 JDBC 模板运行类似的匹配...

SELECT
    id, guid, body, summary, status_id, language_id, is_mce, content_type_id, 
    last_edited_by, locked_by, owner_id, coordinator_id, writer_id, paperless, 
    content_body_type, created, updated, locked_timestamp
FROM dbo.content
WHERE notes LIKE :notes

:notes是必然的%test%,不幸的是它没有返回任何结果。我检查了数据库并验证了该数据是否存在。这不是执行类似匹配的正确方法吗?

更新

生成此查询的部分代码...

    String notes = search.getNotes();
    if (notes instanceof String && notes.length() > 0) {
        if (!previousClause) {
            searchQuery.append("WHERE ");
            previousClause = true;
        }
        searchQuery.append("notes LIKE :notes AND ");
        queryMap.put("notes", "%"+notes+"%");
    }

    Collection<Category> categories = search.getCategoryCollection();
    if (categories != null && categories.size() > 0) {
        Short x = 0;
        for (Category category : categories) {
            searchQuery.append("INNER JOIN dbo.content_to_category AS content_to_category"+x.toString()+" ON (content_to_category"+x.toString()+".category_id IN (:categoryId"+x.toString()+") AND content_to_category"+x.toString()+".content_id = content.id) ");
            queryMap.put("categoryId"+x.toString(), category.getId());
            x++;
        }
    }
4

1 回答 1

0

我假设:(1)您使用的是合理版本的 Hibernate;(2) 上面选择的字段是content's 字段的子集。

应该是这样的:

Criteria crit = session.createCriteria(Content.class);

// add all selected fields:
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("id"));
projList.add(Projections.property("guid"));
projList.add(Projections.property("body"));
projList.add(Projections.property("summary"));
projList.add(Projections.property("status_id"));
projList.add(Projections.property("language_id"));
projList.add(Projections.property("is_mce"));
projList.add(Projections.property("content_type_id"));
projList.add(Projections.property("last_edited_by"));
projList.add(Projections.property("locked_by"));
projList.add(Projections.property("owner_id"));
projList.add(Projections.property("coordinator_id"));
projList.add(Projections.property("writer_id"));
projList.add(Projections.property("coordinator_id"));
projList.add(Projections.property("paperless"));
projList.add(Projections.property("content_body_type"));
projList.add(Projections.property("created"));
projList.add(Projections.property("updated"));
projList.add(Projections.property("locked_timestamp"));
crit.setProjection(projList);

// add a Restriction on notes field, using like:
crit.add(Restrictions.like("notes", "test", MatchMode.ANYWHERE));

// invoke query:
List list = crit.list();

更新

可以肯定的是,您应该使用的正确语法是(依靠直觉和几个博客;我无法确定文档摘录):

Query query = // create long complicated query that ends with "WHERE notes LIKE :notes"
query.setParameter("notes", "%test%");

这在您的情况下可能不起作用的原因是该like运算符适用于varchar操作数等......从您的这段代码看来:

if (notes instanceof String && notes.length() > 0) {

您不确定该字段的基础类型...难道notes不是String吗?

于 2012-05-08T15:27:58.050 回答