Hibernate also needs to be cared for-Hibernate's generic DAO, and hibernate cares for dao

Source: Internet
Author: User

Hibernate also needs to be cared for-Hibernate's generic DAO, and hibernate cares for dao

Objects are based on abstraction. It can also be said that abstraction promotes continuous development of programming. For database access, I have written HqlHelper and EFHelper. Writing applications under the Spring + Hibernate framework is also unable to write a general generic GenericHibernateDao. I have reviewed many GenericHibernateDao implementations on the Internet and summarized them into the following implementations for future coding reference.


I. 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 Serializable, PK extends Serializable >{// ------------------ Basic Search, add, modify, and delete operations -------- ------------ // Obtain the object based on the primary key. If no corresponding entity exists, null is returned. Public T get (PK id); // obtains and locks an object based on the primary key. If no corresponding entity exists, null is returned. Public T getWithLock (PK id, LockMode lock); // obtain the object based on the primary key. If no corresponding entity exists, an exception is thrown. Public T load (PK id); // obtains and locks an object based on the primary key. If no corresponding entity exists, an exception is thrown. Public T loadWithLock (PK id, LockMode lock); // obtain all objects. Public List <T> loadAll (); // loadAllWithLock ()? // Update the object public void update (T entity); // update the object and lock the public void updateWithLock (T entity, LockMode lock ); // store the entity to the database public void save (T entity); // saveWithLock () // Add or update the entity public void saveOrUpdate (T entity ); // Add or update all objects in the set public void saveOrUpdateAll (Collection <T> entities); // delete the specified object public void delete (T entity ); // lock and delete the specified object public void deleteWithLock (T entity, LockMode lock); // Delete the specified object public void deleteByKey (PK id) based on the primary key ); // lock the primary key and delete the specified object public void deleteByKeyWithLock (PK id, LockMode lock); // delete all objects in the set public void deleteAll (Collection <T> entities ); // -------------------- HQL ------------------------------------------------ // use the HQL statement to add, update, and delete the public int bulkUpdate (String queryString) object ); // use the HQL statement with parameters to add, update, and delete entities public int bulkUpdate (String queryString, Object [] values ); // use the HQL statement to retrieve the public List find (String queryString) data; // use the HQL statement with parameters to retrieve the public List find (String queryString, Object [] values) data ); // retrieve the public List findByNamedParam (String queryString, String [] paramNames, Object [] values) using the HQL statement with the name parameter ); // use the named HQL statement to retrieve the data public List findByNamedQuery (String queryName); // use the named HQL statement with parameters to retrieve the data public List findByNamedQuery (String queryName, object [] values); // use the HQL statement with the name parameter to retrieve the public List of data findByNamedQueryAndNamedParam (String queryName, String [] paramNames, Object [] values ); // use the HQL statement to retrieve data and return Iterator public Iterator iterate (String queryString); // use the HQL statement with the parameter to retrieve data and return Iterator public Iterator iterate (String queryString, object [] values); // disable Iterator public void closeIterator (Iterator it) returned by the retrieval ); // retrieve Criteria ------------------------------ // create a standard Object public DetachedCriteria createDetachedCriteria (); // create a standard Object public Criteria createCriteria () bound to the session (); // use the specified retrieval standard to retrieve public List findByCriteria (DetachedCriteria criteria); // use the specified retrieval standard to retrieve data, and return partial public List findByCriteria (DetachedCriteria criteria, int firstResult, int maxResults); // use the specified object and attribute to retrieve (satisfying the attribute = object value except the primary key) data public List <T> findEqualByEntity (T entity, String [] propertyNames ); // use the specified object and attribute (non-primary key) to retrieve (satisfying the like String object Value) data public List <T> findLikeByEntity (T entity, String [] propertyNames ); // use the specified retrieval standard to retrieve data and return the public Integer getRowCount (DetachedCriteria criteria) Record of the specified range; // use the specified retrieval standard to retrieve data, return the specified public Object getStatValue (DetachedCriteria criteria, String propertyName, String StatName); // specify Others attributes // lock the specified Object public void lock (T entity, LockMode lockMode ); // force initialize the specified Object public void initialize (Object proxy); // force update the buffered data to the database immediately (otherwise, the data is updated only when the transaction is committed) public void flush ();}

Ii. GenericDao interface implementation class 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. crit Erion. 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 inherits the HibernateDao, encapsulates the functions of HibernateTemplate, and * simplifies the compilation of Hibernate-based Dao. ** @ Author lianhai */@ SuppressWarnings ("unchecked") public class GenericHibernateDao <T extends Serializable, PK extends Serializable> extends HibernateDaoSupport implements GenericDao <T, PK >{// object Class type (automatically assigned by the constructor) private Class <T> entityClass; // constructor automatically obtains the object Class public GenericHibernateDao () based on the instance Class () {this. entityClass = null; Class c = getClass (); Type t = c. getGenericSuperclass (); if (t instanceof Para MeterizedType) {Type [] p = (ParameterizedType) t ). getActualTypeArguments (); this. entityClass = (Class <T>) p [0] ;}// -------------------- Basic Search, add, modify, and delete operations ------------------ // obtain the object based on the primary key. If no corresponding entity exists, null is returned. Public T get (PK id) {return (T) getHibernateTemplate (). get (entityClass, id) ;}// obtain and lock an object based on the primary key. If no corresponding entity exists, 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;} // obtain the object based on the primary key. If no corresponding entity exists, an exception is thrown. Public T load (PK id) {return (T) getHibernateTemplate (). load (entityClass, id) ;}// obtain the entity based on the primary key and lock it. If no corresponding entity exists, an exception is thrown. 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;} // obtain all objects. Public List <T> loadAll () {return (List <T>) getHibernateTemplate (). loadAll (entityClass);} // loadAllWithLock ()? // Update the public void update (T entity) {getHibernateTemplate (). update (entity);} // update the object and lock public void updateWithLock (T entity, LockMode lock) {getHibernateTemplate (). update (entity, lock); this. flush (); // refresh immediately; otherwise, the lock will not take effect.} // Store the entity to the database public void save (T entity) {getHibernateTemplate (). save (entity);} // saveWithLock ()? // Add or update the public void saveOrUpdate (T entity) {getHibernateTemplate (). saveOrUpdate (entity);} // Add or update all entities in the set public void saveOrUpdateAll (Collection <T> entities) {getHibernateTemplate (). saveOrUpdateAll (entities);} // delete the specified object public void delete (T entity) {getHibernateTemplate (). delete (entity);} // lock and delete the specified object public void deleteWithLock (T entity, LockMode lock) {getHibernateTemplate (). delete (e Ntity, lock); this. flush (); // refresh immediately, otherwise the lock will not take effect.} // Delete the specified object public void deleteByKey (PK id) {this. delete (this. load (id);} // lock and delete the specified object public void deleteByKeyWithLock (PK id, LockMode lock) {this. deleteWithLock (this. load (id), lock);} // delete all objects in the set public void deleteAll (Collection <T> entities) {getHibernateTemplate (). deleteAll (entities);} // -------------------- HQL -------------------------------------------------- // use the HSQL statement to add, update, and delete data directly. Except the public int bulkUpdate (String queryString) {return getHibernateTemplate (). bulkUpdate (queryString);} // use the HQL statement with parameters to add, update, and delete public int bulkUpdate (String queryString, Object [] values) {return getHibernateTemplate (). bulkUpdate (queryString, values);} // use the HQL statement to retrieve the public List find (String queryString) {return getHibernateTemplate (). find (queryString);} // use the HQL statement with parameters to retrieve the public List find (Str Ing queryString, Object [] values) {return getHibernateTemplate (). find (queryString, values);} // use the HQL statement with the name of the parameter to retrieve the data public List findByNamedParam (String queryString, String [] paramNames, Object [] values) {return getHibernateTemplate (). findByNamedParam (queryString, paramNames, values);} // retrieve data using the named HSQL statement public List findByNamedQuery (String queryName) {return getHibernateTemplate (). findByNamedQue Ry (queryName) ;}// use the named HQL statement with parameters to retrieve the public List findByNamedQuery (String queryName, Object [] values) {return getHibernateTemplate (). findByNamedQuery (queryName, values);} // use a named HQL statement with a name parameter to retrieve the public List of data: findByNamedQueryAndNamedParam (String queryName, String [] paramNames, Object [] values) {return getHibernateTemplate (). findByNamedQueryAndNamedParam (queryName, paramNames, values);} // use the HQL statement to check Return Iterator public Iterator iterate (String queryString) {return getHibernateTemplate (). iterate (queryString);} // use the HQL statement with parameters to retrieve data. Iterator public Iterator iterate (String queryString, Object [] values) {return getHibernateTemplate () is returned (). iterate (queryString, values);} // disable Iterator public void closeIterator (Iterator it) {getHibernateTemplate (). closeIterator (it );}//--------------------- ----------- Criteria ---------------------------- // create a session-independent retrieval standard public DetachedCriteria createDetachedCriteria () {return DetachedCriteria. forClass (this. entityClass);} // create the search standard public Criteria createCriteria () {return this. createDetachedCriteria (). getExecutableCriteria (this. getSession ();} // retrieve the public List of compliant data findByCriteria (DetachedCriteria criteria) {return getHibernateTempla Te (). findByCriteria (criteria);} // retrieves compliant data and returns the public List findByCriteria (DetachedCriteria criteria, int firstResult, int maxResults) {return getHibernateTemplate (). findByCriteria (criteria, firstResult, maxResults);} // use the specified object and attribute to retrieve data (except for the primary key property = object Value) public List <T> findEqualByEntity (T entity, string [] propertyNames) {Criteria criteria = this. createCriteria (); Example exam = Example. creat E (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 ();} // use the specified object and attribute to retrieve (satisfying the like String object Value) data public List <T> findLikeByEntity (T entity, String [] propertyNames) {Criteria criteria = this. createCriteria (); for (String property: propertyNames) {try {Object value = PropertyUtils. getProperty (entity, property); if (value instanceof String) {criteria. add (Restrictions. like (property, (String) value, Mat ChMode. ANYWHERE); criteria. addOrder (Order. asc (property);} else {criteria. add (Restrictions. eq (property, value); criteria. addOrder (Order. asc (property) ;}} catch (Exception ex) {// ignore invalid search reference data.} Return (List <T>) criteria. list ();} // use the specified search criteria to obtain the number of records meeting the criteria public Integer getRowCount (DetachedCriteria criteria) {criteria. setProjection (Projections. rowCount (); List list = this. findByCriteria (criteria, 0, 1); return (Integer) list. get (0);} // retrieve data using the specified search criteria. Return the specified statistical value (max, min, avg, sum) public Object getStatValue (DetachedCriteria criteria, String propertyName, string StatName) {if (StatName. toLowerCase (). equals ("max") criteria. setProjection (Projections. 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 ------------------------------ // lock the specified object public void lock (T entity, LockMode lock) {getHibernateTemplate (). lock (entity, lock);} // force initialize the specified Object public void initialize (Object proxy) {getHibernateTemplate (). initialize (proxy);} // force immediately update the buffered data to the database (otherwise it will only be updated when the transaction is committed) public void flush () {getHibernateTemplate (). flush ();}}

The above implementation of the generic Hibernate Dao, the following example is the use of the business object for GenericHibernateDao

3. 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 IArticleDao of the Business Object Article
Define the Dao interface IArticleDao of the Article business object. It inherits from the GenericDao interface to obtain the method. You can add methods specific to the Article Business Object in IArticleDao, or you can directly use all methods provided in GenericDao to specify the type of the business object and the type of the primary key. <Article, Long>

public interface IArticleDAO extends GenericDao <Article,Long> {//    public void findById(Long id);}

V. ArticleHibernateDao class

Now we can define the ArticleHibernateDao class. As long as it implements the IArticleDao interface and inherits the GenericHibernateDao class, we can use all the Generic interfaces and the methods defined in the IArticleDao interface. If you specify the methods specific to the Article business object in the IArticleDao interface, you can implement these methods in ArticleHibernateDao. Methods In the Generic interface have been fully implemented in the parent class GenericHibernateDao of ArticleHibernateDao. You can directly call the methods to access the database.

public class ArticleHibernateDao extends GenericHibernateDao<Article,Long> implements  IArticleDAO {}


Therefore:

Other business objects can also be defined by referring to the Article and ArticleHibernateDao classes. Some common methods in the GenericDao interface are called directly, methods specific to other business objects are defined in the Dao interface of other business objects (inherited from the GenericDao Interface) and implemented through the GenericHibernateDao subclass. Saves a lot of repetitive code. In a few steps, you can use the GenericDao interface implementation class GenericHibernateDao to conveniently access the database.


Supplement:

Finally, we provide a Hibernate ing file for the Article business object and a test class for the ArticleHibernateDao class.

Article ing File

<?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 -->

The test class of ArticleHibernateDao only provides the test code of the seve (article) method.

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 );}}



Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.