2013-01-11

GAE/J+Slim3+Google Cloud SQL+Hibernate+DbUnit(2)

前回の続きで、一覧表示機能について。

ここで使用しているHibernateConfigServiceクラスは、Hibernateの管理用に作成したクラスで、この内容は次回に。

ListControllerクラス
  • setUp()
    • DBのセッションをセッション・スコープに格納して使いまわす
  • run()
    • データ件数の取得(もっと簡潔な方法ないかな?)
      dbSession.createQuery("select count(*) from User")
          .uniqueResult();
    • データの取得:ページングのために、setFirstResult()で取得開始位置を、setMaxResults()で取得件数を指定している
      dbSession.createCriteria(User.class)
          .setFirstResult((pageNo - 1) * MAX_ITEM_PAGE)
          .setMaxResults(MAX_ITEM_PAGE)
          .list();
import org.hibernate.Session;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

public class ListController {
    private final int MAX_ITEM_PAGE = 20;
    private Session _dbSession = null;

    @Override
    protected Navigation setUp() {
        this._dbSession = sessionScope("dbSession");
        if (this._dbSession == null) {
            HibernateConfigService hibernateConfigService = HibernateConfigService.getInstance();
            this._dbSession = hibernateConfigService.getSessionFactory().openSession();
            sessionScope("dbSession", this._dbSession);
        }
        return super.setUp();
    }

    @Override
    public Navigation run() throws Exception {
        List<String> msgList = new ArrayList<String>();
        Session dbSession = getDbSession();

        Long count = (Long)dbSession.createQuery("select count(*) from User").uniqueResult();
        Integer pageNo = asInteger("pageNo");
        if (pageNo == null) { pageNo = 1; }
        requestScope("pageNo", pageNo);
        long maxPageNo = (count - 1) / MAX_ITEM_PAGE + 1;
        requestScope("maxPageNo", maxPageNo);
        List<User> list = (List<User>)dbSession.createCriteria(User.class)
                .setFirstResult((pageNo - 1) * MAX_ITEM_PAGE)
                .setMaxResults(MAX_ITEM_PAGE)
                .list();
        requestScope("list", list);

        return forward("list.jsp");
    }

    protected Session getDbSession() {
        return this._dbSession;
    }
}

0 件のコメント: