Spring3, Hibernate; how do I use HibernateTemplate
Solution 1
Friend friend = new Friend();
friend.setUsername(rUser);
return (List<Friend>) hibernateTemplate.findByCriteria(
DetachedCriteria.forClass(Friend.class)
.add(Example.create(friend)));
or
Friend friend = new Friend();
friend.setUsername(rUser);
return (List<Friend>) hibernateTemplate.findByExample(friend);
or
return (List<Friend>) hibernateTemplate.findByCriteria(
DetachedCriteria.forClass(Friend.class)
.add(Restrictions.eq("username", rUser)));
Solution 2
HibernateTemplate
doesn't provide createCriteria()
method. I guess you need this:
return (List<Friend>) hibernateTemplate.findByExample(friend);
See also:
Solution 3
my advise is exdens HibernateDaoSupport
and inject hibernateTemplate
or sessionFactory
from the xml so you will get protected methods to your DAOImpl class so you can get hibernateTemplate
like this getHibernateTemplate()
and criteria method you can call like this getSession().createCriteria();
Solution 4
First of all have your DAO class extends HIbernateDAOSupport so that you have the getHibernateTemplate() method.
Then use:
getHibernateTemplate().executeFind(new HibernateCallback() {
Object doInHibernate(Session session) {
return session.createCriteria(Friend.class)
.add(Example.create(friend))
.list();
}
});
The template is created when you call setSessionFactory() on your DAO class (add it as a spring dependency to be injected).
The template will then call the doInHibernate() of the supplied callback, passing in the session (which it will obtain from the session factory)
SJS
Updated on December 27, 2020Comments
-
SJS over 3 years
I am trying to change the following code to use: HibernateTemplate but cant it working
public List<Friend> listFriends(String rUser) { hibernateTemplate = new HibernateTemplate(sessionFactory); Friend friend = new Friend(); friend.setUsername(rUser); // This is the old code that worked! return (List<Friend>) sessionFactory.getCurrentSession() .createCriteria(Friend.class) .add(Example.create(friend)) .list(); // This IS THE NEW CODE THAT I CANT GET TO BUILD? return (List<Friend>) hibernateTemplate.createCriteria(Friend.class) .add(Example.create(friend)) .list(); }