Basic HibernateCRUD framework (3)-simple and complex standard CRUD APIs

Source: Internet
Author: User

Advantages: Simple and basic CRUD functions can be quickly implemented, which can be said to be relatively "standardized ". It is easy to maintain.

Disadvantages: The performance is not guaranteed. It does not support complicated CRUD.

Applicable scenarios: Small Web project

1. CrudDao completes the most basic addition, deletion, modification, and query

Including adding an object create, obtaining the object get based on the primary key, updating a Persistent Object update, logically deleting an object remove, logically restoring an object recover, physically deleting a Persistent Object delete, updating properties (TODO, you need to add the where restriction) and update attributes.

Package cn. fansunion. hibernate; import java. lang. reflect. parameterizedType; import java. util. map; import org. hibernate. query; import org. hibernate. session; import org. hibernate. sessionFactory; import org. springframework. beans. factory. annotation. autowired; import cn. fansunion. hibernate. constants. commonConstants; import cn. fansunion. hibernate. constants. statusConstants; import cn. fansunion. hibernate. SQL. update . HqlUpdateBuilder; import cn. fansunion. hibernate. util. Pair;/*** Dao base class to complete the most basic addition, deletion, modification, and query operations. ** @ Author LeiWen@FansUnion.cn */public class CrudDao
 
  
{/*** Object type of the table */protected Class
  
   
ModelClazz; @ Autowired protected SessionFactory sessionFactory; public CrudDao () {this. modelClazz = (Class
   
    
) (ParameterizedType) getClass (). getGenericSuperclass ()). getActualTypeArguments () [0];} //////////////////////////////////////// //// // CRUD ////// //////////////////////////////////////// /// // /////////// *** based on the primary key (unique identifier) query a record ** @ param id * Primary Key * @ return the object corresponding to a record */public T get (Integer id) {T entity = (T) getCurrentSession (). get (modelClazz, id); return entity ;} /*** insert a record to the database ** @ param entity * The object corresponding to the database table */public void create (T entity) {getCurrentSession (). save (entity);}/*** update a record ** @ param entity * object in the persistent state */public void update (T entity) {getCurrentSession (). update (entity);}/*** based on the primary key (unique flag), logically delete a record ** @ param id * Primary Key */public void remove (Integer id) {updateProperties (new Pair (CommonConstants. ID, id), new Pair (CommonConstants. IS_DELETED, StatusConstants. DELETED);}/*** based on the primary key (unique flag), restore a record ** @ param id * Primary Key */public void recover (Integer id) {updateProperties (new Pair (CommonConstants. ID, id), new Pair (CommonConstants. IS_DELETED, StatusConstants. NORMAL);}/*** delete a record physically ** @ param entity * object in the persistent state */public void delete (T entity) {getCurrentSession (). delete (entity);}/*** get primary data source */protected Session getCurrentSession () {return sessionFactory. getCurrentSession ();} //////////////////////////////////////// ////////////// update according to the attribute (TODO adds the where restriction) //////////////////////////////////////// /// // *** update the Attribute Based on 1 (use with caution) ** @ param key * attribute name * @ param value * attribute value * @ return number of updated records */public Integer updateProperty (String key, Object value) {HqlUpdateBuilder builder = new HqlUpdateBuilder (); String hql = builder. param (key, value ). toHql (); return update (hql, key, value);}/*** update based on 0, 1, or multiple attributes (it is strongly recommended that, use at least 2 key-value pairs) */public Integer updateProperties (Pair... pair) {HqlUpdateBuilder builder = new HqlUpdateBuilder (); String hql = builder. param (pair ). toHql (); return update (hql, pair);}/*** update record */public Integer updateProperties (Map
    
     
Params) {HqlUpdateBuilder builder = new HqlUpdateBuilder (); String hql = builder. param (params ). toHql (); return update (hql, params);}/*** Based on hql statements and key-value pairs, update record ** @ param hql * hql statement * @ param key * attribute name * @ param value * attribute value * @ return */public Integer update (String hql, String key, object value) {Map
     
      
Params = createMap (key, value); return update (hql, params);} public Integer update (String hql, Pair... pair) {Map
      
        Params = createMap (pair); return update (hql, params);} public Integer update (String hql, Map
       
         Params) {Query query = createQuery (hql, params); return query.exe cuteUpdate ();} //////////////////////////////////////// /// // create a Query object ////////////// //////////////////////////////////////// ///////////////// protected Query createQuery (String hql, map
        
          Params) {return DaoUtils. createQuery (getCurrentSession (), hql, params);} protected Query createQuery (String hql, String key, Object value) {return DaoUtils. createQuery (getCurrentSession (), hql, key, value);} protected Query createQuery (String hql) {return DaoUtils. createQuery (getCurrentSession (), hql);} protected Map
         
           CreateMap () {return DaoUtils. createMap ();} protected Map
          
            CreateMap (String key, Object value) {return DaoUtils. createMap (key, value);} protected Map
           
             CreateMap (Pair... pair) {return DaoUtils. createMap (pair );}}
           
          
         
        
       
      
     
    
   
  
 

2. BasicQueryUpdateDao provides several common functions.

Including obtaining the total number of records count, obtaining a list, and obtaining a unique result unique.

Package cn. fansunion. hibernate; import java. util. list; import java. util. map; import org. hibernate. query; import cn. fansunion. hibernate. util. emptyUtils; import cn. fansunion. hibernate. util. pageConstants; import cn. fansunion. hibernate. util. pageUtils; import cn. fansunion. hibernate. util. pair;/*** to complete basic query operations. ** @ Author LeiWen@FansUnion.cn */public class BasicQueryUpdateDao
 
  
Extends CrudDao
  
   
{Public static final boolean NOT_PAGE = false; public static final boolean NEED_PAGE = true; //////////////////////////////////////// /// // obtain the total number of records ////////////// //////////////////////////////////////// //// // public Integer count (String hql) {Query query = createQuery (hql); Integer count = doCount (query); return count;} public Integer count (String hql, String key, Object value) {Query query = createQuery (hql, key, value); Integer count = doCount (query); return count;} public Integer count (String hql, Pair... pair) {Map
   
    
Params = createMap (pair); return count (hql, params);} public Integer count (String hql, Map
    
     
Params) {Query query = createQuery (hql, params); Integer count = doCount (query); return count;} protected Integer doCount (Query query) {Integer count = 0; object uniqueResult = query. uniqueResult (); if (uniqueResult! = Null) {count = Integer. parseInt (uniqueResult. toString ();} return count ;} //////////////////////////////////////// //// // obtain a List (generic List is not used.
     
      
) //////////////////////////////////////// //// // Execute an hql query without parameters, returns a result set List public List list (String hql, boolean needPage) {return list (hql, needPage);} public List list (String hql, String key, Object value, boolean needPage) {Map
      
        Params = createMap (key, value); return list (hql, params, needPage);} public List list (String hql, Map
       
         Params, boolean needPage) {if (needPage) {PageUtils. filldefapagpageparams (params);} List list = list (hql, params, needPage); return list;} // execute the private List doList (String hql, map
        
          Params) {Query query = createQuery (hql, params); fillPageParams (query, params); List list = doQuery (query); return list ;} /*** set the paging parameter ** @ param Query * query object * @ param params * Query parameter */private void fillPageParams (query Query, Map
         
           Params) {Integer firstResult = (Integer) params. get (PageConstants. FIRST_RESULT); Integer maxResults = (Integer) params. get (PageConstants. MAX_RESULTS); if (firstResult> 0) {query. setFirstResult (firstResult);} if (maxResults> 0) {query. setMaxResults (maxResults) ;}}/*** execute the query statement ** @ param Query * query object * @ return query result */protected List doQuery (query Query) {return query. list ();} public T unique (String hql) {List
          
            List = list (hql, NOT_PAGE); T result = doGetFirst (list); return result;} public T unique (String hql, String key, Object value) {Map
           
             Params = createMap (key, value); return unique (hql, params);} public T unique (String hql, Pair... pair) {Map
            
              Params = createMap (pair); return unique (hql, params);} public T unique (String hql, Map
             
               Params) {List
              
                List = list (hql, params, NOT_PAGE); T result = doGetFirst (list); return result;} protected T doGetFirst (List
               
                 List) {T result = null; if (EmptyUtils. notEmpty (list) {result = list. get (0) ;}return result ;}}
               
              
             
            
           
          
         
        
       
      
     
    
   
  
 


3. BasicSqlQueryUpdateDao

Use native SQL instead of HQL to implement some common functions, similar to BasicQueryUpdateDao.

More functions, similar to the above. The encapsulation degree is different.

4. BaseDao

More similar features

SearchListByProperty: Fuzzy search for matching result sets based on one or more key-value pairs

FindListByProperty: Precisely searches for Objects Based on a key-Value Pair

FindByPropertyUnique: Precisely searches for an object based on one key-Value Pair

CountFindByPropertyListAnd: count the number of query records

5. More API

More functions need to be sorted out according to actual needs...

Summary

The most basic and common function of website development is to add, delete, modify, and query CRUD.

Both Hibernate and Mybatis have their own advantages and disadvantages.

If you think about problems from the perspective of development and technology, there will always be endless problems and countless repeated code.

Without thinking about and summing up, programmers of the rich and handsome grades will also be made code farmers and tortured.

Original article link: Http://blog.fansunion.cn/articles/3624 (Xiao Lei blog-blog.fansunion.cn)

Related Article

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.