Hibernate SQLQuery - Get an object by name

I have a way to get a category by its "id", and I need a similar method to get a category by its "name". I used these methods using Hibernate. How can I fix my second method to get a category by name? My source code is as follows:

// 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 thrown at 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 to the people.

+5
source share
1 answer

If you are sure that your table has only one entry for each category, you can use Query # uniqueResult :

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

Make sure you handle the exceptions thrown by uniqueResult.

+4
source

Source: https://habr.com/ru/post/1202615/


All Articles