java Hibernate SQLQuery - 按名称获取对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25856304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:48:32  来源:igfitidea点击:

Hibernate SQLQuery - Get Object by name

javaspringhibernatesessionfactory

提问by wilson

I have a method to get a Category by its "id" and I need a similar method to get a Category by its "name". I did these methods by using Hibernate. How can I fix my second method to get a Category by name? My source code is as follow:

我有一种通过“id”获取类别的方法,我需要一个类似的方法来通过“名称”获取类别。我使用 Hibernate 完成了这些方法。如何修复我的第二种方法以按名称获取类别?我的源代码如下:

// It works
@Override
public Category getById(int id) {
    return (Category) sessionFactory.getCurrentSession().get(Category.class, id);
}

// It doesn't works
@Override
public Category getByName(String name) {
    return (Category) sessionFactory.getCurrentSession().
        createSQLQuery("SELECT FROM Category WHERE name="+name);
}

I have this error with the second method:

第二种方法我有这个错误:

java.lang.ClassCastException: org.hibernate.impl.SQLQueryImpl cannot be cast to com.sedae.model.Category

java.lang.ClassCastException: org.hibernate.impl.SQLQueryImpl 不能转换为 com.sedae.model.Category

These are my controllers.

这些是我的控制器。

@RequestMapping(value = "/getCategoryById/{id}")
public String getCategoryById(Model model, @PathVariable ("id") int id){
    model.addAttribute("category", categoryService.getById(id));
    return "/getCategoryById";
}

@RequestMapping(value = "/getCategoryByName/{name}")
public String getCategoryByName(Model model, @PathVariable("name") String name){
    model.addAttribute("category", categoryService.getByName(name));
    return "/getCategoryByName";
}

Thanks in advance people.

在此先感谢人们。

回答by user3487063

If you are sure you have only one entry per category name in your table then you can use Query#uniqueResult:

如果您确定表中每个类别名称只有一个条目,那么您可以使用Query#uniqueResult

Query query= sessionFactory.getCurrentSession().
        createQuery("from Category where name=:name");
query.setParameter("name", name);
Category category = (Category) query.uniqueResult();

Make sure to handle the exceptions thrown by uniqueResult.

确保处理由 uniqueResult 抛出的异常。