Hibernate Sqlquery - Get Object by Name

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:

// 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

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.

1 Answer

If you are sure you have only one entry per category name in your table then 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 to handle the exceptions thrown by uniqueResult.

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest