Hibernate "DAO Refactoring and Advanced Paging"

Source: Internet
Author: User

Hibernate refactoring DAO Ideas:

First step: Implement generic DAO interface and implementation class

Core technology:

(1) When the new subclass () is called, the subclass invokes the constructor of the parent class, at which point the parent class can learn about the child class

(2) Hibernate metadata, which is the data that describes the persisted class data

Second step: For different table operations, inherit the DAO implementation class (in order to pass generics), and do not have to do any overwrite

Step three: Manipulate what table, call what DAO

Refactoring DAO Instance: The first step: universal interface and implementation

Interface:

 Public Interface Commondao<t> {    public list<t> getallentity ();       Public Long GetCount ();}

Implementation class:

 Public classCommondaoimpl<t>ImplementsCommondao<t> {    PrivateClass Class1; PrivateClassmetadata Classmetadata;  PublicCommondaoimpl () {Parameterizedtype Parameterizedtype= (Parameterizedtype) This. GetClass (). Getgenericsuperclass (); Class1= (Class) parameterizedtype.getactualtypearguments () [0]; Classmetadata=HibernateUtils.sessionFactory.getClassMetadata (Class1); } @Override PublicList<t>getallentity () {sessionfactory sessionfactory=hibernateutils.getsessionfactory (); Session Session=sessionfactory.opensession (); List<T> list=session.createquery ("from" +class1.getname ()). List ();        Session.close (); returnlist; }

The second step: for different table operations, to inherit the common implementation class
 Public class extends commondaoimpl<classes> {}
Step Three: Use
        Classesdao classesdao=New  Classesdao ();        System.out.println (Classesdao.getallentity ());

Hibernate pre-compilation

To implement paging, you have to mention precompilation, because I need conditional stitching, which can be precompiled in hibernate in two ways.

Way One:

Query query=session.createquery ("from Domain. Student where name=? " );        Query.setparameter (0, "King two Dog");

Way two:

        Query query=session.createquery ("from Domain. Student where Name=:name ");        Query.setparameter ("name", "King two Dog");

Hibernate Advanced Paging

The use of Hibernate advanced paging is nothing more than a common form of how query conditions are written. The challenge is how to handle paging requests and write out a generic solution.

  

Core Technologies used: the use of abstract classes

(i) Design abstract data type (ADT)-pagination class

All of our paging information is in instances of this class.

 Public classPageresult<t> {    PrivateString URL;//values that need to be set    PrivateList<t> datas;//the value obtained from the database    /*** CurrentPage and pagesize are the data that we need to pass in, and other data can be obtained by calculation*/    Private intCurrentPage;//the value passed over    Private intPageSize;//the value passed over        Private intPagestartindex;//constructor in the set    Private intTotaldatas;//Pass it over.    Private intTotalPages;//constructor Function        Private intFirstPage; Private intLastPage; Private intNextPage; Private intPrevPage;  PublicPageresult (Basequery basequery,intTotaldatas) {         This. currentpage=Basequery.getcurrentpage ();  This. totaldatas=Totaldatas;  This. pagesize=basequery.getpagesize (); TotalPages=totaldatas%pagesize==0?totaldatas/pagesize:totaldatas/pagesize+1; Pagestartindex= (currentPage-1) *pageSize; /*** so that the current page is always in the middle of the page number*/        if(totalpages>3) {//Here's 3 to say that there are several indexes per pageFirstpage=currentpage-1; LastPage=currentpage+1; if(firstpage<1) {FirstPage=1; LastPage=3; }            if(lastpage>totalpages) {FirstPage=totalpages-2; LastPage=TotalPages; }        }Else{firstpage=1; LastPage=TotalPages; }    }
Pageresult

Analysis:

The current page and how many are displayed per page, both of which are an indicator of a paged query. Is that we are in the dynamic, so the two properties are whatever, and the conditions of the multi-conditional query is not certain, we need to let the user to dynamically increase the query conditions. So we encapsulate these required paging properties together.

(ii) Querying common interfaces

 Public Abstract class basequery {    public  Integer currentpage;      Public Integer pageSize;      Public Map<string, object> keyvalues;      Public Abstract Map<string, object> somecondition ();        Getter and setter:}
View Code

(c) Universal interface implementation class

@Override PublicPageresult<t>Getpagedata (Basequery basequery) {sessionfactory sessionfactory=hibernateutils.getsessionfactory (); Session Session=sessionfactory.opensession (); //Calculate Total PagesLong nums= (long) session.createquery ("Select count (" +classmetadata.getidentifierpropertyname () + ") from" +class1.getname ()). Uniqueresult (); //Pageresult requires two parameters, and a series of calculations are done internallyPageresult<t> pageresult=NewPageresult<t>(Basequery, Nums.intvalue ()); //Stitching Query ConditionsStringBuffer stringbuffer=NewStringBuffer (); Stringbuffer.append ("From" +class1.getname ()); Stringbuffer.append ("Where 1=1");  for(Map.entry<string, object>entry:baseQuery.someCondition (). EntrySet ()) {Stringbuffer.append ("and" +entry.getkey () + "=:" +entry.getkey () + ""); } System.out.println ("Stitching the SQL statement as:" +StringBuffer); Query Query=Session.createquery (stringbuffer.tostring ());  for(Map.entry<string, object>entry:baseQuery.someCondition (). EntrySet ())        {Query.setparameter (Entry.getkey (), Entry.getvalue ());        } query.setmaxresults (Pageresult.getpagesize ());        Query.setfirstresult (Pageresult.getpagestartindex ()); List<T> lists=query.list ();        Pageresult.setdatas (lists); returnPageresult; }
View Code

(iv) General DAO

@Override PublicPageresult<t>Getpagedata (Basequery basequery) {sessionfactory sessionfactory=hibernateutils.getsessionfactory (); Session Session=sessionfactory.opensession (); //Calculate Total PagesLong nums= (long) session.createquery ("Select count (" +classmetadata.getidentifierpropertyname () + ") from" +class1.getname ()). Uniqueresult (); //Pageresult requires two parameters, and a series of calculations are done internallyPageresult<t> pageresult=NewPageresult<t>(Basequery, Nums.intvalue ()); //Stitching Query ConditionsStringBuffer stringbuffer=NewStringBuffer (); Stringbuffer.append ("From" +class1.getname ()); Stringbuffer.append ("Where 1=1");  for(Map.entry<string, object>entry:baseQuery.getKeyValues (). EntrySet ()) {Stringbuffer.append ("and" +entry.getkey () + "=:" +entry.getkey () + ""); } System.out.println ("Stitching the SQL statement as:" +StringBuffer); Query Query=Session.createquery (stringbuffer.tostring ());  for(Map.entry<string, object>entry:baseQuery.getKeyValues (). EntrySet ())        {Query.setparameter (Entry.getkey (), Entry.getvalue ());        } query.setmaxresults (Pageresult.getpagesize ());        Query.setfirstresult (Pageresult.getpagestartindex ()); List<T> lists=query.list ();        Pageresult.setdatas (lists); returnPageresult; }
View Code

(v) Use

Studentdao studentdao=New  Studentdao ();                Studentquery studentquery=new  studentquery ();        Studentquery.setname ("Floret");                Studentquery.setcurrentpage (2);        Studentquery.setpagesize (2);            Pageresult<Student> pageresult=studentdao.getpagedata (studentquery);        List<Student> students=pageresult.getdatas ();          for (Student s:students) {            System.out.println (S.getid ());        }
View Code

Hibernate "DAO Refactoring and Advanced Paging"

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.