SJS
SJS

Reputation: 5667

Spring3, Hibernate; how do I use HibernateTemplate

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();
}

Upvotes: 7

Views: 31095

Answers (5)

user4395645
user4395645

Reputation: 11

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();

Upvotes: 1

Andrei Fierbinteanu
Andrei Fierbinteanu

Reputation: 7826

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)

Upvotes: 1

RichN
RichN

Reputation: 6241

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)));

Upvotes: 19

axtavt
axtavt

Reputation: 242786

HibernateTemplate doesn't provide createCriteria() method. I guess you need this:

return (List<Friend>) hibernateTemplate.findByExample(friend);

See also:

Upvotes: 1

Nathanphan
Nathanphan

Reputation: 957

did you initialize sessionFactory? If you initialize sessionFactory correctly, so make your class, which conatians the above method, extends HibernateDAOSupport class which have getHibernateTemplate() method.

Upvotes: 0

Related Questions