The object-oriented foundation of the week is abstraction. It can also be said that abstraction drives programming to evolve. For access to the database, Hqlhelper,efhelper has been written. Writing an application under the Spring+hibernate framework is also not a generic generic generichibernatedao to write. Look up a lot of online Generichibernatedao implementation, summed up for the following implementation, for subsequent coding reference.
One, DAO generic interface Genericdao
Package Ict.framework.orm.hibernate;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 Lianhai */public interface Genericdao<t extends SERIALIZABL E, 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); Add or 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); --------------------HQL----------------------------------------------//Use HQL statement to directly add, UPDATE, delete entity public int BULKUPD Ate (String queryString); Add, UPDATE, delete entity public int bulkupdate (String queryString, object[] values) using the HQL statement with parameters; Retrieving data using the HQL statement public List Find (String queryString); Retrieving data using a HQL statement with parameters public List find (String queryString, object[] values); Retrieving data using HQL statements with named parameters public List Findbynamedparam (String queryString, string[] paramnames,object[] values); Retrieving data using the named HQL Statement public List findbynamedquery (String queryname); Using a life with parametersThe name HQL statement retrieves the data public List findbynamedquery (String queryname, object[] values); Retrieving data using named HQL statements with named parameters public List Findbynamedqueryandnamedparam (String queryname, string[] paramnames, object[] Values ); Retrieving data using the HQL statement, returning Iterator public Iterator iterate (String queryString); Retrieves data using the parameter HQL 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, returning part of the record public List Findbycriteria (detachedcriteria criteria, int firstresult, int maxResults); 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); Retrieved using the specified entity and attribute (non-primary key) (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 statname); --------------------------------Others--------------------------------//Locking the specified entity public void Lock (T entity, Lockmode 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 ();
second, the realization class of Genericdao interface Generichibernatedao
Package Ict.framework.orm.hibernate.impl;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 Lianhai */@SuppressWarnings ("Unchecked") public class Generichibernatedao<t extends Serializable, PK exten DS Serializable> extends Hibernatedaosupport implements Genericdao<t, pk> {//entity class type (automatically assigned by construction method) Private Cla Ss<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); }//--------------------HQL----------------------------------------------//Use the HSQL statement to directly add, update, and delete entity public int b Ulkupdate (String queryString) {return gethibernatetemplate (). Bulkupdate (queryString); }//Use HQL statement with parameters to add, update, delete entity public int bulkupdate (String queryString, object[] values) {return gethibernatete Mplate (). Bulkupdate (queryString, values); }//Use the HQL statement to retrieve data Public List Find (String queryString) {return gethibernatetemplate (). Find (queryString); }//Use the HQL statement with parameters to retrieve the data public List find (String queryString, object[] values) {return gethibernatetemplate (). Fi nd (queryString, values); }//Use HQL statement with named parameter to retrieve data public List Findbynamedparam (String queryString, string[] paramnames, object[] values) { 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 HQL statement with parameter to retrieve data public List findbynamedquery (String queryname, object[] values) {return gethibernatet Emplate (). Findbynamedquery (queryname, values); }//Use named HQL statement with named parameter to retrieve data public List Findbynamedqueryandnamedparam (String queryname, string[] paramnames, object[] V Alues) {return gethibernatetemplate (). Findbynamedqueryandnamedparam (Queryname,paramnames, ValUES); }//Use HQL statement to retrieve data, return Iterator public Iterator iterate (String queryString) {return gethibernatetemplate (). iter Ate (queryString); }//Use the parameter HQL statement to retrieve the data, return Iterator public Iterator iterate (String queryString, object[] values) {return gethibe Rnatetemplate (). 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 ()); }//Retrieve data that meets the criteria public List Findbycriteria (Detachedcriteria criteria) {return gethibernatetemplate (). FINDBYCR Iteria (criteria); }//Retrieve data that satisfies the criteria, returns the record of the specified range PUBlic List Findbycriteria (detachedcriteria criteria, int firstresult, int maxResults) {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 get the number of records that meet the criteria 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 entit Y, LocKmode lock) {gethibernatetemplate (). 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 is the implementation of the generic Hibernate Dao, the following example is the use of business objects to Generichibernatedao
Third, the business object article
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; } public void SetContent (String content) { this.content = content; }}
Iv. DAO interface for business object article Iarticledao
Defines the DAO interface Iarticledao for the article business object, which inherits from the Genericdao interface to obtain the methods in it. 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 primary key <Article,Long>
Public interface Iarticledao extends Genericdao <Article,Long> {//Public void FindByID (Long id);}
Five, Articlehibernatedao class
Now it is possible to define the Articlehibernatedao class, as long as it implements the Iarticledao interface and inherits the Generichibernatedao class, all the Generic interfaces and the methods defined 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.
public class Articlehibernatedao extends generichibernatedao<article,long> implements Iarticledao {}
So
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.
Tween
Finally, we provide a Hibernate mapping file for the article business object and a test class for the Articlehibernatedao class .
mapping files for article
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd "><!--Article.hbm.xml-->
Articlehibernatedao test class that provides only the test code for the Seve (article) methodpublic 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);} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Hibernate also needs to take care of--hibernate's generic DAO