The summary of SSH integration--using hibernatetemplate to realize the data page display

Source: Internet
Author: User

In a large number of data display, you have to use paged query, the first use of the SSH framework in the integration of the use of paged query, encountered some problems, below, I practice the project as an example in detail, how to complete the data paging query in Spring+hibernate (+action) environment.

Create a new Pagebean under the Utils package (this entity class is used to encapsulate the data collection of the current page, and the parameters related to page):

 Public classPagebean<t> {    Private intPage//Current Page    Private intTotalCount;//Total Record Count    Private intTotalpage;//Total Pages (total number of records/records per page)    Private intLimit//number of records per page    PrivateList<t> list;//contains a collection of items//Set/get Method omitted}

In my case, on the page, when you click on "All Items", you will jump into the (action Class) goodsaction, and pass in a parameter page, which defaults to 1.

Goodsaction:

 Public classGoodsactionextendsActionsupportImplementsModeldriven<goods>, servletrequestaware{PrivateGoodsservice Goodsservice; PrivateGoods goods=NewGoods ();        HttpServletRequest request; Private intpage; /*** Show All items *@return     */     PublicString ShowAll () {//list<goods> Glist=goodsservice.findall ();Pagebean<goods> pagebean=goodsservice.findbypage (page); Actioncontext.getcontext (). Getvaluestack (). Set ("Pagebean", Pagebean); return"FINDALL_SUCC"; }         Public voidSetgoodsservice (Goodsservice goodsservice) { This. Goodsservice =Goodsservice; } @Override PublicGoods Getmodel () {returngoods; } @Override Public voidsetservletrequest (HttpServletRequest request) { This. request=request; }     Public voidSetpage (intpage) {         This. page =page; }     Public intGetPage () {returnpage; }}

In action, you need to return information for all private members that get Pagebean, and set it to the top of the value stack (valuestack) stack for page echo calls.

Here is Goodsservice:

 PackageCom.wang.shop.goods.service;Importjava.util.List;ImportCom.wang.shop.goods.dao.GoodsDao;ImportCom.wang.shop.goods.entity.Goods;ImportCom.wang.shop.util.PageBean; Public classGoodsservice {PrivateGoodsdao Goodsdao;  Public voidSetgoodsdao (Goodsdao Goodsdao) { This. Goodsdao =Goodsdao; }     PublicPagebean<goods> Findbypage (intpage) {Pagebean<Goods> Pagebean =NewPagebean<goods>();        Pagebean.setpage (page); intLimit=4;        Pagebean.setlimit (limit); intTotalcount=Goodsdao.findtotalcount ();        Pagebean.settotalcount (TotalCount); intTotalpage= (int) Math.ceil (totalcount/limit);        Pagebean.settotalpage (Totalpage); //collection of data displayed per page        intbegin= (page-1) *limit; List<Goods> list=Goodsdao.findbypageid (Begin,limit);        Pagebean.setlist (list); returnPagebean; }    }

In the service, setting each property of Pagebean can get the direct setting, not getting the database query in the DAO layer.

Goodsdao:

 PackageCom.wang.shop.goods.dao;Importjava.util.List;ImportOrg.springframework.orm.hibernate4.HibernateCallback;ImportOrg.springframework.orm.hibernate4.support.HibernateDaoSupport;ImportCom.wang.shop.goods.entity.Goods;ImportCom.wang.shop.util.PageHibernateCallback; Public classGoodsdaoextendshibernatedaosupport{ PublicList<goods>FindAll () {List<Goods> list= (list<goods>) This. Gethibernatetemplate (). Find ("from Goods"); returnlist; }     PublicGoods FindByID (intGoodsid) {Goods Goods= This. Gethibernatetemplate (). Get (Goods.class, Goodsid); returngoods; }     //Query the total number of records in the goods table     Public intFindtotalcount () {String hql= "SELECT count (*) from Goods"; List<Long> list= (list<long>) This. Gethibernatetemplate (). Find (HQL); if(list!=NULL&&list.size () >0){            returnList.get (0). Intvalue (); }        return0; }    //Query the product collection for the current page     PublicList<goods> FindByPageID (intBeginintlimit) {String hql= "From Goods"; List<Goods> list= (list<goods>) This. Gethibernatetemplate (). Execute ((hibernatecallback<goods>)NewPagehibernatecallback (HQL,Newobject[]{}, begin, limit)); if(list!=NULL&&list.size () >0){                        returnlist; }        return NULL; }}

Notice here that I used a pagehibernatecallback class, usually we would write a hibernatecallback anonymous inner class, and then write the relevant code inside, for the code reuse, Here we re-write a class to implement the Hibernatecallback interface, and then through the generic dependency injection, you can get a tool class. Here is the code.

Pagehibernatecallback:

 PackageCom.wang.shop.util;Importjava.sql.SQLException;Importjava.util.List;Importorg.hibernate.HibernateException;ImportOrg.hibernate.Query;Importorg.hibernate.Session;ImportOrg.springframework.orm.hibernate4.HibernateCallback; Public classPagehibernatecallback<t>ImplementsHibernatecallback<list<t>>{        PrivateString hql; Privateobject[] params; Private intStartIndex; Private intpageSize;  PublicPagehibernatecallback (String hql, object[] params,intStartIndex,intpageSize) {        Super();  This. HQL =hql;  This. params =params;  This. StartIndex =StartIndex;  This. pageSize =pageSize; }     PublicList<t> Doinhibernate (Session session)throwshibernateexception {query Query=session.createquery (HQL); if(Params! =NULL){             for(inti = 0; i < params.length; i + +) {Query.setparameter (I, params[i]);        }} query.setfirstresult (StartIndex);                Query.setmaxresults (pageSize); returnquery.list (); }}

The second parameter in the construction method of the above code is an array of type Object, used to set the "?" in the HQL statement, and if you do not have this parameter, it can be written as new object[]{} at the time of the call.

The above can be achieved, the data paged query.

The summary of SSH integration--using hibernatetemplate to realize the data page display

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.