Volodymyr Levytskyi
Volodymyr Levytskyi

Reputation: 3432

How to do hibernate pagination in spring bean?

I have spring dao bean called HostelDaoImpl. It uses hibernate criteria api to retrieve results.

public class HostelDaoImpl extends AbstractGenericDao<Hostel, Integer> implements HostelDao {

    public HostelDaoImpl() {
        super(Hostel.class);
    }

    public List<Hostel> findHostelBy(HostelSearch hs) {
            Criteria criteria = currenSession().createCriteria(Hostel.class);
            criteria.setReadOnly(true);

            Calendar beginDate = hs.getBeginDate();
            String country = hs.getCountry();

            if (beginDate != null)
                criteria.add(Restrictions.le("beginDate", beginDate));

            if (country != null) {
                criteria.add(Restrictions.eq("country", country));
            }

            criteria.setProjection(Projections.rowCount());
            Integer foundHostelsCount = (Integer) criteria.uniqueResult();

            if (foundHostelsCount > 100) {
                // do pagination
            }
    }
}

Now in place of those comments I need pagination. I want to create Criteria only once and then store Criteria somewhere and call Criteria's setFirstResult and setMaxResults each time when user requests new portion of data.

Where to store Criteria if spring bean HostelDaoImpl is singleton and if I create instance variable Criteria criteria it is concurrently unsafe.

Where to store Criteria so that it is thread safe?

But if you know better way to achieve hibernate pagination in spring bean please provide it.

Thanks!

Upvotes: 2

Views: 2177

Answers (3)

Harshal Patil
Harshal Patil

Reputation: 6759

You can use pageRequest for pagination. follow the steps on this link. This link is very helpful. The link explains everything till JSP page.

Upvotes: 0

darkquester
darkquester

Reputation: 42

I'm using the Jquery plugin JQGrid to show in a table the results, and it's very easyly to hibernate pagination.

http://jqgrid.com/

Upvotes: 1

Evgeny Makarov
Evgeny Makarov

Reputation: 1448

You can use CRUD repositories. It supports pagination

http://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

Upvotes: 4

Related Questions