glig glig - 1 year ago 258
Java Question

uniqueResult is deprecated in hibernate 5.2.2 ?how i can do?

hi,everyone i am a newcomer for hibernate. i write code with struts+spring+hibernate ,i encounter a trouble in this code

import org.hibernate.Query;
import com.integration.entity.User;
public class UserDAOImpl extends HibernateDaoSupport implements UserDAO {
public User getUser(String name) {
// TODO Auto-generated method stub
String hsql="from User u where'"+name+"'";
User result=(User)((Query) this.getHibernateTemplate().find(hsql)).uniqueResult();
return result;

the question is Query and uniqueResult() is deprecated ,how will i modify my code? thanks

Answer Source

The problem is not only in your method. The hole class HibernateDaoSupportis deprecated as it said here

I recommend you to configure your SessionFactory via Spring (as I see you use it) and use createQuery method to pass there your hql. Here is the example:

Configuring session factory:

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"

The DAO method:

private final SessionFactory sessionFactory;

// Injecting session factory via constructor
public UserDAO(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;

String hql="from User u where";

public User getByUsername(String name) {
    return sessionFactory.getCurrentSession()
            .createQuery(hql, User.class)
            .setParameter("name", name)

Also your code us not secure. You should use params of query for preventing sql injections. I show it in my method. Read about session factory and injecting it in DAO.

Good luck.


Also it's just an example. You can configure everything as you wish (via java code, not xml for example)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download