glig glig - 27 days ago 17
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 org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.integration.entity.User;
public class UserDAOImpl extends HibernateDaoSupport implements UserDAO {
@Override
public User getUser(String name) {
// TODO Auto-generated method stub
String hsql="from User u where u.name='"+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

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"
      p:packagesToScan="-your-model-"
      p:hibernateProperties-ref="-your-properties-"
      p:dataSource-ref="-your-datasource-"/>

The DAO method:

private final SessionFactory sessionFactory;

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

String hql="from User u where u.name=:name";

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

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.


EDIT

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

Comments