mysql - 就像运算符(operator)不工作一样,使用 spring mvc 和 hibernate

标签 mysql hibernate spring-mvc sql-like operator-keyword

好的,所以我对 Java 和 hibernate 还是有点新手,我正在尝试在我的数据库中搜索问题/答案集,如果我输入准确的内容,我可以很好地调出该集问题,但是当我使用 like 运算符时没有任何效果,而且我真的不确定该怎么做。我只是在搜索问题,它与答案是同一个对象的一部分,所以我也只是用它来提取答案。

这是我在 QuestionAnswerDao 中的代码

    public QuestionAnswerSet getQuestionAnswerSetByQuestion(String question)
{
    Session session = (Session) em.getDelegate();

    return (QuestionAnswerSet)   session.createCriteria(QuestionAnswerSet.class).add(Restrictions.eq("question", "%"+question+"%")).uniqueResult();
}

这也是我 Controller 中的代码

    @RequestMapping(value="search", method=RequestMethod.GET)
public String searchGet (ModelMap model, HttpServletRequest request)
{
    SearchForm searchForm = new SearchForm();

    model.put("searchForm", searchForm);
    return "app/search";
}

@RequestMapping(value="search", method=RequestMethod.POST)
public String searchPost (@ModelAttribute("searchForm") SearchForm searchForm, ModelMap model, HttpServletRequest request)
{
    QuestionAnswerSet questionAnswerSetByQuestion = questionAnswerDao.getQuestionAnswerSetByQuestion(searchForm.getSearchString());
    model.put("searchResult", questionAnswerSetByQuestion);

    return "app/search";
}

如果有人能帮我解决这个问题,那就太好了,谢谢。

最佳答案

我在你的例子中没有看到“喜欢”,但我认为你只需要改变 Restrictions.eq ro Restrictions.like.

所以如果使用 Hibernate 4.3,这将是这个方法:

https://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/criterion/Restrictions.html#like(java.lang.String , java.lang.Object)

我认为之后的“uniqueResult”有点令人担忧,如果您使用通配符进行搜索,我总是会假设可能会有不止一个结果。如果存在 uniqueResult 方法,则可能会抛出异常。

此外,在 Hibernate 配置中启用“show_sql”总是有助于查看 Hibernate 在开发过程中生成的实际 sql。

关于mysql - 就像运算符(operator)不工作一样,使用 spring mvc 和 hibernate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32916421/

相关文章:

java - 下载 CSV 格式的完整数据库

HTML 不要在 Spring 应用程序中使用我的 css

Mysql 用聚合和注释表

php - 给出警告 : mysql_fetch_assoc() expects parameter 1 to be resource, 字符串

java - 如何与3张 table 进行通信

java - @Formula注释不理解 "count"

java - 使用 springmvc 和 hibernate 运行我的 Maven 项目时出错

mysql - Prestashop 1.6 : query to add product weight to all items

mysql - Hive 中未显示的特殊字符

json - 如何使用 Hibernate 映射 postgresql json 数据类型?