【问题标题】:Like operator not working, using spring mvc and hibernate像操作员不工作,使用spring mvc和hibernate
【发布时间】:2015-12-31 05:02:35
【问题描述】:

好的,所以我仍然是 Java 和休眠的新手,我正在尝试在我的数据库中搜索一个问题/答案集,如果我输入确切的内容,我可以很好地提取该集问题,但是当我使用 like 运算符时没有任何效果,我真的不知道该怎么做。我只是在搜索问题,它与答案属于同一对象,所以我也只是将答案拉出来。

这是我的 QuestionAnswerDao 中的代码

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

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

这也是我在控制器中的代码

    @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";
}

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

【问题讨论】:

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


    【解决方案1】:

    我在您的示例中没有看到“喜欢”,但我认为您只需要更改 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。

    【讨论】:

    • 谢谢,效果很好。我只是将我的代码更改为 Restrictions.like。此外,您对“uniqueResult”抛出异常是正确的。我取出了“uniqueResult”代码,现在我没有搜索任何作品。你有什么建议吗?这就是我的代码现在的样子return (QuestionAnswerSet) session.createCriteria(QuestionAnswerSet.class).add(Restrictions.like("question", "%"+question+"%"));
    • 其实我觉得是我的jsp有问题,我没有c:forEach循环
    • 是的,你需要说“forList()”,然后将返回类型作为列表类型处理。最终,您可以检查列表是否有超过 0 个项目,然后返回最后一个(如果您确定它将是您想要的项目)。
    • 我想通了,我只是在唯一结果的位置添加了 .list() 并将返回类型处理为列表类型更新了控制器。我将如何在我的 .jsp 中返回结果列表,现在我正在使用像这样的 <c:if test="${!empty searchResult}"> <div id="HomeAnswer" style="font-weight: bold;"><p>${searchResult.answer}</p></div> <div id="HomeQuestion" style="font-weight: bold;"><p>${searchResult.question}</p></div> </c:if> 但它只返回一个,就像我所期望的那样,我只是不知道如何返回所有最接近的相关结果。
    猜你喜欢
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 2011-03-29
    相关资源
    最近更新 更多