Hibernate generalization Template Dao

Source: Internet
Author: User

Writing an application under the Spring+hibernate framework is always a common generic generichibernatedao. Look up a lot of online Generichibernatedao implementation, summed up for the following implementation, for subsequent coding reference.

First define the interface generic DAO interface Genericdao

Package Com.th.huz;import Java.io.serializable;import Java.util.collection;import java.util.iterator;import Java.util.list;import Org.hibernate.criteria;import Org.hibernate.lockmode;import  org.hibernate.criterion.detachedcriteria;/** * * @author lny */public interface genericdao<t extends Serializable, PK Extends Serializable> {//--------------------basic Search, add, modify, delete operations--------------------//Get entities based on primary key.    If there is no corresponding entity, NULL is returned.    Public T get (PK ID); Gets the entity and locks it based on the primary key.    If there is no corresponding entity, NULL is returned.    Public T Getwithlock (PK ID, Lockmode lock); Gets the entity based on the primary key.    Throws an exception if there is no corresponding entity.    Public T load (PK ID); Gets the entity and locks it based on the primary key.    Throws an exception if there is no corresponding entity.    Public T Loadwithlock (PK ID, Lockmode lock);    Gets all entities.    Public list<t> Loadall ();    Loadallwithlock ()?    Update entity public void Update (T entity);    Update entities and lock public void Updatewithlock (T entity, Lockmode Lock);    Store entity to database public void Save (T entity);    Savewithlock ()//Add or update entity public void Saveorupdate (T entity); Increaseor update all entities in the collection public void Saveorupdateall (collection<t> entities);    Deletes the specified entity public void Delete (T entity);    Locks and deletes the specified entity public void Deletewithlock (T entity, Lockmode Lock);    Deletes the specified entity public void Deletebykey (PK ID) According to the primary key;    Locks on the primary key and deletes the specified entity public void Deletebykeywithlock (PK ID, Lockmode lock);    Delete all entities in the collection public void DeleteAll (collection<t> entities); --------------------HSQL----------------------------------------------//Use HSQL statement to directly add, UPDATE, delete entity public int Bulku    Pdate (String queryString);    Add, UPDATE, delete entity public int bulkupdate (String queryString, object[] values) using the Hsql statement with parameters;    Retrieving data using the HSQL statement public List Find (String queryString);    Retrieving data using a HSQL statement with parameters public List find (String queryString, object[] values); Retrieving data using Hsql statements with named parameters public List Findbynamedparam (String queryString, string[] paramnames, object[] Values    );    Retrieving data using the named Hsql Statement public List findbynamedquery (String queryname); Using named HS with parametersQL statement retrieving data public List findbynamedquery (String queryname, object[] values); Retrieving data using named Hsql statements with named parameters public List Findbynamedqueryandnamedparam (String queryname, string[] paramnames, OBJ    Ect[] values);    Retrieving data using the Hsql statement, returning Iterator public Iterator iterate (String queryString);    Retrieves data using the parameter Hsql statement, returning Iterator public Iterator iterate (String queryString, object[] values);    Close retrieves the returned Iterator public void Closeiterator (Iterator it); --------------------------------Criteria------------------------------//Create a session-independent retrieval standard object public Detachedcriteri    a Createdetachedcriteria ();    Create a search criteria object for session binding public criteria Createcriteria ();    Retrieves data using the specified retrieval criteria public List Findbycriteria (Detachedcriteria criteria); Retrieves data using the specified retrieval criteria, returns a partial record public List Findbycriteria (detachedcriteria criteria, int firstresult, int maxresult    s);    Retrieves data using the specified entities and attributes (satisfies the attribute except the primary KEY = entity value) public list<t> findequalbyentity (T entity, string[] propertynames); Use refers toEntity and attribute (non-primary key) retrieved (satisfies the attribute like string entity value) data public list<t> findlikebyentity (T entity, string[] propertynames);    Retrieves data using the specified retrieval criteria, returning the specified range of records public Integer GetRowCount (Detachedcriteria criteria); Retrieves data using the specified retrieval criteria, returns the specified statistic value public Object getstatvalue (Detachedcriteria criteria, String propertyname, String S    Tatname); --------------------------------Others--------------------------------//Locking the specified entity public void Lock (T entity, Lo    Ckmode Lockmode);    Forces the initialization of the specified entity public void Initialize (Object proxy); Force immediate updating of buffered data to the database (otherwise only updated when transaction commits) public void flush ();

Implementation class for hibernate that implements the Genericdao interface Generichibernatedao

Import Java.lang.reflect.parameterizedtype;import Java.io.serializable;import Java.lang.reflect.ParameterizedType ; Import Java.lang.reflect.type;import Java.util.collection;import java.util.iterator;import Java.util.List;import Org.apache.commons.beanutils.propertyutils;import Org.hibernate.criteria;import Org.hibernate.LockMode;import Org.hibernate.criterion.detachedcriteria;import Org.hibernate.criterion.example;import Org.hibernate.criterion.matchmode;import Org.hibernate.criterion.order;import Org.hibernate.criterion.projections;import Org.hibernate.criterion.restrictions;import org.springframework.orm.hibernate3.support.hibernatedaosupport;/** * Generichibernatedao inherit HibernateDao, simple package Hibernatetemplate features, * simplifies writing based on Hibernate Dao. * * @author Lny */@SuppressWarnings ("Unchecked") public class Generichibernatedao<t extends Serializable, PK extends Se Rializable> extends Hibernatedaosupport implements Genericdao<t, pk> {//entity class type (automatically assigned by construction method) Private C lass<T> Entityclass;        Constructor method, automatically gets the entity class Type Public Generichibernatedao () {this.entityclass = null based on the instance class;        Class C = getclass ();        Type t = C.getgenericsuperclass ();            if (t instanceof Parameterizedtype) {type[] p = ((Parameterizedtype) t). Getactualtypearguments ();        This.entityclass = (class<t>) p[0]; }}//--------------------basic Retrieve, add, modify, delete operations--------------------//Get entities based on primary key.    If there is no corresponding entity, NULL is returned.    Public T get (PK ID) {return (T) gethibernatetemplate (). Get (Entityclass, id); }//The entity is acquired and locked according to the primary key.    If there is no corresponding entity, NULL is returned.        Public T Getwithlock (PK ID, Lockmode lock) {T t = (t) gethibernatetemplate (). Get (Entityclass, ID, lock);        if (t! = null) {This.flush ();//refresh immediately, otherwise the lock will not take effect.    } return t; }//Gets the entity based on the primary key.    Throws an exception if there is no corresponding entity.    Public T load (PK ID) {return (T) gethibernatetemplate (). Load (entityclass, id); }//The entity is acquired and locked according to the primary key.    Throws an exception if there is no corresponding entity. Public T Loadwithlock (PK ID, LOckmode lock) {T t = (t) gethibernatetemplate (). Load (Entityclass, ID, lock);        if (t! = null) {This.flush ();//refresh immediately, otherwise the lock will not take effect.    } return t;    }//Get all entities.    Public list<t> Loadall () {return (list<t>) gethibernatetemplate (). Loadall (Entityclass);    }//Loadallwithlock ()?    Update entity public void Update (T entity) {gethibernatetemplate (). Update (entity); }//Update entity and lock public void Updatewithlock (T entity, Lockmode Lock) {gethibernatetemplate (). Update (Entity, lock        ); This.flush ();    Refresh immediately, or the lock will not take effect.    }//Store entity to database public void Save (T entity) {gethibernatetemplate (). Save (entity);    }//Savewithlock ()?    Add or update entity public void Saveorupdate (T entity) {gethibernatetemplate (). Saveorupdate (entity); }//Add or update all entities in the collection public void Saveorupdateall (collection<t> entities) {gethibernatetemplate (). Saveoru    Pdateall (entities); }//delete the specified entity public VOID Delete (T entity) {gethibernatetemplate (). Delete (entity); }//Locking and deletes the specified entity public void Deletewithlock (T entity, Lockmode Lock) {gethibernatetemplate (). Delete (Entity, l        Ock); This.flush ();    Refresh immediately, or the lock will not take effect.    }//delete the specified entity public void Deletebykey (PK id) {This.delete (This.load (ID)) According to the primary key; }//Lock on the primary key and delete the specified entity public void Deletebykeywithlock (PK ID, Lockmode lock) {This.deletewithlock (This.load (ID)    , lock); }//Delete all entities in the collection public void DeleteAll (collection<t> entities) {gethibernatetemplate (). DeleteAll (Entiti    ES); }//--------------------HSQL----------------------------------------------//Add, UPDATE, delete entity public int directly using HSQL statement    Bulkupdate (String queryString) {return gethibernatetemplate (). Bulkupdate (queryString); }//Use HSQL statement with parameters to add, update, delete entity public int bulkupdate (String queryString, object[] values) {return gethibernatet    Emplate (). Bulkupdate (queryString, values); }//using the Hsql languageThe sentence retrieves the data public List find (String queryString) {return gethibernatetemplate (). Find (queryString); }//Use the HSQL statement with parameters to retrieve the data public List find (String queryString, object[] values) {return gethibernatetemplate (). f    IND (queryString, values); }//Use HSQL statement with named parameter to retrieve data public List Findbynamedparam (String queryString, string[] paramnames, object[] V    Alues) {return gethibernatetemplate (). Findbynamedparam (queryString, paramnames, values); }//Use the named Hsql statement to retrieve the data public List findbynamedquery (String queryname) {return gethibernatetemplate (). Findbynam    Edquery (queryname); }//Use named Hsql statement with parameter to retrieve data public List findbynamedquery (String queryname, object[] values) {return gethibernate    Template (). Findbynamedquery (queryname, values); }//Use named Hsql statement with named parameter to retrieve data public List Findbynamedqueryandnamedparam (String queryname, string[] Paramnames , object[] values) {return gethibernatetemplate (). FindbynAmedqueryandnamedparam (QueryName, paramnames, values); }//Use HSQL statement to retrieve data, return Iterator public Iterator iterate (String queryString) {return gethibernatetemplate (). ite    Rate (queryString); }//Use the parameter Hsql statement to retrieve the data, return Iterator public Iterator iterate (String queryString, object[] values) {return Gethib    Ernatetemplate (). Iterate (queryString, values);    }//Close retrieves the returned Iterator public void Closeiterator (Iterator it) {gethibernatetemplate (). Closeiterator (it); }//--------------------------------criteria------------------------------//Create a session-independent retrieval standard public detachedcrit    Eria createdetachedcriteria () {return detachedcriteria.forclass (This.entityclass); }//Create search criteria for session binding public criteria Createcriteria () {return This.createdetachedcriteria (). Getexecutablecriter    IA (This.getsession ()); }//Retrieving data that meets the criteria public List Findbycriteria (Detachedcriteria criteria) {return GethibernatetemplatE (). Findbycriteria (criteria); }//Retrieves data that satisfies the criteria, returns the record of the specified range public List Findbycriteria (detachedcriteria criteria, int firstresult, int maxre    Sults) {return gethibernatetemplate (). Findbycriteria (Criteria, firstresult, maxResults);        }//Use the specified entity and attribute to retrieve (satisfy except for primary key attribute = entity value) data public list<t> findequalbyentity (T entity, string[] propertynames) {        Criteria = This.createcriteria ();        Example exam = example.create (entity);        Exam.excludezeroes ();        string[] Defpropertys = Getsessionfactory (). Getclassmetadata (Entityclass). Getpropertynames ();            for (String defproperty:defpropertys) {int II = 0;                    for (ii = 0; II < propertynames.length; ++ii) {if (Defproperty.equals (Propertynames[ii])) {                    Criteria.addorder (ORDER.ASC (Defproperty));                Break }} if (ii = = propertynames.length) {EXam.excludeproperty (Defproperty);        }} criteria.add (exam);    Return (list<t>) criteria.list ();        }//using the specified entity and attribute to retrieve (satisfies the attribute like string entity value) data public list<t> findlikebyentity (T entity, string[] propertynames) {        Criteria = This.createcriteria (); for (String property:propertynames) {try {Object value = Propertyutils.getproperty (entity, p                Roperty);                            if (value instanceof String) {Criteria.add (Restrictions.like (property, (String) value,                    Matchmode.anywhere));                Criteria.addorder (Order.asc (property));                    } else {Criteria.add (Restrictions.eq (property, value));                Criteria.addorder (Order.asc (property));            }} catch (Exception ex) {//ignores invalid retrieval reference data.    }} return (list<t>) criteria.list (); }//Use the specified retrieval criteria to obtain records that meet the criteriaNumber public Integer GetRowCount (Detachedcriteria criteria) {criteria.setprojection (Projections.rowcount ());        List List = This.findbycriteria (criteria, 0, 1);    Return (Integer) list.get (0); Retrieves data using the specified retrieval criteria, returns the specified statistic value (max,min,avg,sum) public Object getstatvalue (detachedcriteria criteria, String Propertynam E, String statname) {if (Statname.tolowercase (). Equals ("Max")) Criteria.setprojection (Projec        Tions.max (PropertyName));        else if (Statname.tolowercase () Equals ("Min")) Criteria.setprojection (Projections.min (PropertyName));        else if (statname.tolowercase (). Equals ("avg")) Criteria.setprojection (Projections.avg (PropertyName));        else if (statname.tolowercase (). Equals ("sum")) Criteria.setprojection (Projections.sum (PropertyName));        else return null;        List List = This.findbycriteria (criteria, 0, 1);    Return List.get (0); }    // --------------------------------Others--------------------------------//Locking the specified entity public void Lock (T entity, Lockmode Lock) {Gethibern    Atetemplate (). Lock (entity, lock);    }//Forces initialization of the specified entity public void Initialize (Object proxy) {gethibernatetemplate (). Initialize (proxy);    }//force immediate updating of buffered data to the database (otherwise only updated when transaction commits) public void flush () {gethibernatetemplate (). Flush (); }}

The above code from the online collection

The above is the implementation of the generic Hibernate Dao, the following example is the use of business objects to Generichibernatedao

Business Object Article aticle table for the corresponding article table

Package Com.th.huz.model;import Java.io.serializable;import Java.util.date;public class article implements    Serializable {private static final long serialversionuid = 1072812006693587010L;    Private long ID;    Private String title;    Private String author;    Private Date pubDate;    Private String content;    Public long GetId () {return id;    } public void SetId (long id) {this.id = ID;    } public String GetTitle () {return title;    public void Settitle (String title) {this.title = title;    } public String Getauthor () {return author;    } public void Setauthor (String author) {this.author = author;    Public Date Getpubdate () {return pubDate;    } public void Setpubdate (Date pubDate) {this.pubdate = pubDate;    } public String GetContent () {return content;    The public void SetContent (String content) {this.content = content; }}

Defines the DAO interface Iarticledao for the article business object, which inherits from the Genericdao interface to obtain the method

You can add article business object-specific methods in Iarticledao, or you can use all the methods provided in Genericdao Iarticledao interface to specify the type of business object and the type of the primary key

Package Com.th.huz.model;import Com.th.huz.dao.genericdao;import Com.th.huz.model.article;public interface Iarticledao extends Genericdao <Article,Long> {//Public    void FindByID (Long id);}

The Articlehibernatedao class can then be defined, as long as it implements the Iarticledao interface and inherits the Generichibernatedao class so that all the Generic interfaces and the defined methods in the Iarticledao interface can be used. If you specify a method that is specific to the article business object in the Iarticledao interface, implement these methods in Articlehibernatedao. The method in the generic interface is fully implemented in the Articlehibernatedao parent class Generichibernatedao, and the database can be accessed conveniently by direct invocation.

Package Com.th.huz.model;import Com.th.huz.dao.generichibernatedao;public Class Articlehibernatedao extends Generichibernatedao<article,long> implements        Iarticledao {}

Other business objects can also be defined by reference to the article and Articlehibernatedao classes, and the common methods in the Genericdao interface are called directly, not enough to be replenished later, other business object-specific methods are on the DAO interface of other business objects ( Inherited from the Genericdao interface) is defined and implemented by the Generichibernatedao subclass. Save a lot of duplicate code, simple steps can use the Genericdao interface implementation class Generichibernatedao easy access to the database.

Finally, we provide a Hibernate mapping file and a SQL script for the article business object and a test class for the Articlehibernatedao class.

mapping files for article

<id name= "id" type= "java.lang.Long" ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd "><!--Article.hbm.xml--> 

Article table script for the corresponding article table

if exists (SELECT * from dbo.sysobjects WHERE id = object_id (N ' [dbo].[ Article] ') and OBJECTPROPERTY (ID, N ' isusertable ') = 1) drop table [dbo]. [Article] Gocreate TABLE [dbo]. [Article] (    [id] [int] IDENTITY (1, 1) not NULL,    [title] [varchar] (+) COLLATE chinese_prc_ci_as not NULL,    [author] [varchar]  (+) COLLATE chinese_prc_ci_as null,    [pubDate] [datetime] NULL,    [content] [text] COLLATE chinese_prc_ci_as null ) on [PRIMARY] textimage_on [Primary]go

Articlehibernatedao test class that provides only the test code for the Seve (article) method

Package Com.th.huz.test;import Junit.framework.testcase;import Org.springframework.context.ApplicationContext; Import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.th.huz.model.article;import Com.th.huz.model.articlehibernatedao;public class Articlehibernatedaotest extends TestCase {    ApplicationContext CTX = new Classpathxmlapplicationcontext (            "Applicationcontext.xml");    Articlehibernatedao ADH = (Articlehibernatedao) ctx            getbean ("Articlehibernatedao");    public void Testsave () {        Article art = (article) Ctx.getbean ("article");        Art.setid (1);        Art.settitle ("Title 1");        Art.setauthor ("author 1");        Adh.save (art);}    }

The above code in the integrated Hibernate Spring framework debugging through, only for learning reference, please self-collocation of your environment to debug, I am also a beginner, there is no clear place please advise.

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.