The implementation of general DAO Layer and service layer based on spring and hibernate _hibernate

Source: Internet
Author: User

Because the DAO layer is basically crud operation, the change is not very big, if there is a change is the query. There is no need to write a complete DAO for each entity, but not yet, then "extract" it. and the service dependency and DAO layer, sometimes just a simple call, there is no need to write each. In short, do not love to write multiple, then write a generic, and other inheritance or implementation of this generic can be.

Let's talk in code.

Package Org.monday.dao;   Import java.io.Serializable;      Import java.util.List; /** * Basedao defines a common operation for DAO * * @author Monday/public interface basedao<t> {public void save T          entity);          public void update (T entity);          public void Delete (Serializable ID);          Public T FindByID (Serializable ID);      Public list<t> findbyhql (String hql, Object ... params); }

The DAO above only defines some common methods, there is a need for common methods, you can add, and then implement it on the line.
package org.monday.dao.impl;      import java.io.serializable;   Import  java.lang.reflect.ParameterizedType;   import java.util.list;      import javax.annotation.resource;      import org.hibernate.query;   import org.hibernate.session;   import org.hibernate.sessionfactory;   Import  org.monday.dao.BaseDao;     /**   * BaseDaoImpl  The implementation of a common operation to define DAO    *    *  @author  Monday   */   @SuppressWarnings (" Unchecked ")    public class basedaoimpl<t> implements basedao<t>  {          private Class<T> clazz;           /**       *  Specify DAO's concrete implementation class     by constructing method     */       public basedaoimpl ()  {            ParameterizedType type =  (Parameterizedtype)  this.getclass (). Getgenericsuperclass ();           clazz =  (Class <T>)  type.getactualtypearguments () [0];            SYSTEM.OUT.PRINTLN ("DAO's True Implementation class is:"  + this.clazz.getname ());       }           /**       *  inject sessionfactory to DAO layer        */        @Resource         private SessionFactory sessionFactory;          /* *       *  Get current work session       */        protected session getsession ()  {            return this.sessionfactory.getcurrentsession ();       }           public void save (t entity)  {            this.getsession (). Save (entity);       }           public void update (t entity)  {           this.getsession (). Update (entity);        }          public void delete (serializable id )  {           this.getsession (). Delete (This.findbyid (ID) );       }          public T  FindByID (SErializable id)  {           return  (T)   This.getsession (). Get (This.clazz, id);       }        &NBSP;&NBSP;&NBSP;PUBLIC&NBSP;LIST&LT;T&GT;&NBSP;FINDBYHQL (String hql, object... params)  {            query query = this.getsession (). CreateQuery (HQL);           for  (int i =  0; params != null && i < params.length; i++)  {                query.setparameter (i,  params);           }            return query.list ();       }  } 

The above is the Basedao and its implementation class.

The following take Customerdao and Orderdao as an example, the preparation of specific DAO package Org.monday.dao;      Import Org.monday.domain.Customer;          /** * Customer DAO Inherits Basedao * * @author Monday/public interface Customerdao extends basedao<customer> { /** * If Basedao does not have a defined method, you can add */} here
package org.monday.dao.impl;      import org.monday.dao.customerdao;   import org.monday.domain.customer;   import org.springframework.stereotype.repository;      /**   *  Customer DAO Implementation class   Inheritance basedaoimpl  Show client DAO interface    *     *  @author  Monday   */   @Repository (value =  "Customerdao")    public class customerdaoimpl extends basedaoimpl<customer>  implements customerdao {          /**        *  If customerdao  defines a method that Basedao does not have, you can implement it here        */   }  

 
package org.monday.dao;      import org.monday.domain.order;      /**   *  order DAO inheritance basedao   *    *  @author   monday   */   public interface orderdao extends basedao<order>  {       /**       *  If basedao  does not have a defined method , where you can add        */  } 

Package Org.monday.dao.impl;   Import Org.monday.dao.OrderDao;   Import Org.monday.domain.Order;      Import Org.springframework.stereotype.Repository; /** * Order DAO Implementation class inheritance Basedaoimpl display Order DAO interface * * @author Monday/@Repository (value = "Orderdao") public class Or       Derdaoimpl extends basedaoimpl<order> implements Orderdao {/** * If Orderdao defines a method that Basedao does not have, you can implement it here */   }

As for the specific service how to write it. Look below:
Package org.monday.service;   Import java.io.Serializable;      Import java.util.List; /** * Baseservice defines the general operation of the service * * @author Monday/public interface Baseservice<t> {public          void Save (T entity);          public void update (T entity);          public void Delete (Serializable ID);          Public T GetByID (Serializable ID);   Public list<t> getbyhql (String hql, Object ... params); }
package org.monday.service.impl;      import java.io.serializable;   import java.util.list;      import javax.annotation.resource;       import org.monday.dao.basedao;   import org.monday.service.baseservice;   import org.springframework.transaction.annotation.transactional;        /**    * BaseServiceImpl  implementation of general operations for service    *    *  @author   monday   */   @Transactional    public class baseserviceimpl<t>  implements BaseService<T> {               /**       *  injection of basedao       */        private BaseDao<T> dao;         @Resource       public void setdao (Basedao<t> dao)  {            this.dao = dao;        }          public void save (t entity)  {            dao.save (entity);       }           public void update (t entity)  {           dao.update (entity);       }           public void delete (serializable id)  {            dao.delete (ID);       }           public t getbyid (serializable id)  {    &NBSP;        return dao.findbyid (ID);       }           public list<t> getbyhql (string hql,  Object... params)  {           return  DAO.FINDBYHQL (hql, params);       }  } 

Package org.monday.service;      Import Org.monday.domain.Customer; /** * Customer Service Inherits Baseservice * * @author Monday * * Public interface CustomerService extends Baseservice<cust omer> {/** * If Baseservice does not have a defined method, it can be added here * *}

package org.monday.service.impl;      import javax.annotation.resource;       import org.monday.dao.basedao;   import org.monday.domain.customer;    import org.monday.service.customerservice;   import  org.springframework.stereotype.service;   import  org.springframework.transaction.annotation.transactional;     /**   *  Implementation class   Inheritance of customer service baseserviceimpl  display customer service interface    *    *  @author   monday   */      @Service ("CustomerService")    @Transactional    Public class customerserviceimpl extends baseserviceimpl<customer> implements  CustomerService {          /**        *  Injection dao       */        @Resource (name =  "Customerdao")        public void  Setdao (Basedao<customer> dao)  {            Super.setdao (dao);       }          /**        *  If customerservice  defines a method that Baseservice does not have, you can implement     here     */     } 

Package org.monday.service;      Import Org.monday.domain.Order; /** * Order service Inherits Baseservice * * @author Monday * * Public interface OrderService extends BASESERVICE<ORDER&G T {/** * If Baseservice does not have a defined method, you can add * * here}

package org.monday.service.impl;      import javax.annotation.resource;       import org.monday.dao.basedao;   import org.monday.domain.order;    import org.monday.service.orderservice;   import  org.springframework.stereotype.service;   import  org.springframework.transaction.annotation.transactional;     /**   *  Order service implementation Class   inheritance baseserviceimpl  display order service interface    *    *  @author   monday   */      @Service (value =  "OrderService")    @ transactional   Public class orderserviceimpl extends baseserviceimpl<order > implements OrderService {          /**        *  Injection dao       */        @Resource (name =  "Orderdao")        public void setdao ( Basedao<order> dao)  {           super.setdao ( DAO);       }          /**        *  If customerservice  defines a method that Baseservice does not have, you can implement it here         */  } 

Here is just a way to provide a thought. Perhaps the code is still not rigorous place, welcome to add a correction.

Two exceptions that are easy to appear:

1.org.hibernate.hibernateexception:no hibernate session bound to thread, and configuration does not allow creation of non -transactional one here

Answer: To add @transactional annotation

In addition to adding annotations here

@Service ("CustomerService")
@Transactional

public class Customerserviceimpl extends baseserviceimpl<customer> implements CustomerService {}

I want to add it here.

@Transactional

public class Baseserviceimpl<t> implements baseservice<t> {}

2.org.springframework.beans.factory.beancreationexception:error creating Bean with Name ' CustomerService ':
Injection of resource fields failed;
Nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [Org.monday.dao.BaseDao] is defined:
Expected single matching Bean but found 2: [Customerdao, Orderdao]

Answer:

Reference

Inject the specific DAO

@Resource (name= "Customerdao")
public void Setdao (Basedao<customer> dao) {
Super.setdao (DAO);
}

PS: Draw a picture well.












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.