Using Generics to extract Dao layers and add transaction annotations (java. lang. Class cannot be cast to java. lang. reflect. ParameterizedType)

Source: Internet
Author: User

Using Generics to extract Dao layers and add transaction annotations (java. lang. Class cannot be cast to java. lang. reflect. ParameterizedType)

If you want to use generics to extract the BaseDao layer, the following problems may occur during simplified operations:

@ Transactional The annotation can be inherited, so I want to write it on the extracted BaseDao layer so that the implemented class can start the transaction without having to write @ Transactional.

Problem description:

The Code is as follows:

Package com. liang. ssh2.base; import java. lang. reflect. parameterizedType; import java. util. collections; import java. util. list; import javax. annotation. resource; import org. hibernate. query; import org. hibernate. session; import org. hibernate. sessionFactory; import org. springframework. transaction. annotation. transactional; import com. liang. ssh2.config. configuration; import com. liang. ssh2.entity. page; import com. liang. ssh2.util. queryHelper; @ Transactional @ SuppressWarnings ("unchecked") public class BaseDao
 
  
{@ Resourceprivate SessionFactory sessionFactory; Class
  
   
Clazz;/*** obtain the parameter type through reflection */public BaseDaoImpl () {System. out. println (this); ParameterizedType pt = (ParameterizedType) this. getClass (). getGenericSuperclass (); clazz = (Class
   
    
) Pt. getActualTypeArguments () [0];}/*** get the currently available Session * @ return */protected Session getSession () {return sessionFactory. getCurrentSession ();}/* (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # save (T) */public void save (T entity) {getSession (). save (entity);}/* (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # getById (java. lang. long) */public T getById (Long id) {if (id = null) return null; return (T) get Session (). get (clazz, id);}/* (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # update (T) */public void update (T entity) {getSession (). update (entity);}/* (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # delete (java. lang. long) */public void delete (Long id) {if (id! = Null) {Object entity = getById (id); if (entity! = Null) {getSession (). delete (entity) ;}}/ * (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # getByIds (java. lang. long []) */public List
    
     
GetByIds (Long [] ids) {if (ids = null | ids. length = 0) {return Collections. EMPTY_LIST;} return getSession (). createQuery (// "from" + clazz. getSimpleName () + "where id in (: ids )")//. setParameterList ("ids", ids )//. list ();}/* (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # findAll () */public List
     
      
FindAll () {return getSession (). createQuery (// "from" + clazz. getSimpleName ())//. list ();}/* (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # getPage (long, java. lang. long, com. liang. ssh2.util. queryHelper) */public Page getPage (long currentPage, Long pageSize, QueryHelper queryHelper) {// if you do not specify pageSize dynamically, read the configuration file if (pageSize = null) {pageSize = Configuration. getPageSize ();} // obtain the parameter List
      Parameters = queryHelper. getParameters (); Query query = getSession (). createQuery (queryHelper. getQueryListHql (); if (parameters! = Null & other meters. size ()> 0) {for (int I = 0; I <parameters. size (); I ++) {query. setParameter (I, parameters. get (I) ;}} query. setFirstResult (int) (currentPage-1) * pageSize); query. setMaxResults (pageSize. intValue (); List recordList = query. list (); // query the total number of records query = getSession (). createQuery (queryHelper. getQueryCountHql (); // note the space! If (parameters! = Null & parameters. size ()> 0) {// set the parameter for (int I = 0; I <parameters. size (); I ++) {query. setParameter (I, parameters. get (I) ;}} Long recordCount = (Long) query. uniqueResult (); // query return new Page (currentPage, pageSize, recordCount, recordList );}}



Use:

package com.liang.ssh2.service.impl;import org.springframework.stereotype.Service;import com.liang.ssh2.base.BaseDao;import com.liang.ssh2.entity.User;@Servicepublic class UserServiceImpl extends BaseDao
        
         {}
        

Note that I put @ Transactional on BaseDao. Because @ Transactional can be inherited, UserServiceImpl does not need to be placed.

When the server is started, the following error occurs: Caused by: java. lang. ClassCastException: java. lang. Class cannot be cast to java. lang. reflect. ParameterizedType.

Why?

After testing for half a day, I found that the error occurred on BaseDao: @ Transactional. The reason is not clear !!!

Two solutions:

1. Directly remove the @ Transactional Annotation on BaseDao and add @ Transactional to the implementation class. In this example, add @ Transactional to UserServiceImpl to start the transaction and no error will be reported!

2. Don't be lazy. Just give BaseDao an interface. You don't need to change anything else. @ Transactional can still be inherited. The modification code is as follows:

Package com. liang. ssh2.base; import java. util. List; import com. liang. ssh2.entity. Page; import com. liang. ssh2.util. QueryHelper; public interface BaseDao
        
         
{/*** Save the object * @ param entity */public abstract void save (T entity ); /*** obtain the object by id * @ param id * @ return */public abstract T getById (Long id); public abstract void update (T entity ); public abstract void delete (Long id); public abstract List
         
          
GetByIds (Long [] ids); public abstract List
          
           
FindAll ();/*** get page * @ param currentPage * @ param pageSize // if the user does not dynamically specify pageSize (null ), read the configuration file * @ param queryHelper * @ return */public abstract Page getPage (long currentPage, Long pageSize, QueryHelper queryHelper );}
          
         
        

Package com. liang. ssh2.base; import java. lang. reflect. parameterizedType; import java. util. collections; import java. util. list; import javax. annotation. resource; import org. hibernate. query; import org. hibernate. session; import org. hibernate. sessionFactory; import org. springframework. transaction. annotation. transactional; import com. liang. ssh2.config. configuration; import com. liang. ssh2.entity. page; import com. liang. ssh2.util. queryHelper; @ Transactional @ SuppressWarnings ("unchecked") public class BaseDaoImpl
        
         
Implements BaseDao
         
          
{@ Resourceprivate SessionFactory sessionFactory; Class
          
           
Clazz;/*** obtain the parameter type through reflection */public BaseDaoImpl () {System. out. println (this); ParameterizedType pt = (ParameterizedType) this. getClass (). getGenericSuperclass (); clazz = (Class
           
            
) Pt. getActualTypeArguments () [0];}/*** get the currently available Session * @ return */protected Session getSession () {return sessionFactory. getCurrentSession ();}/* (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # save (T) */public void save (T entity) {getSession (). save (entity);}/* (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # getById (java. lang. long) */public T getById (Long id) {if (id = null) return null; return (T) get Session (). get (clazz, id);}/* (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # update (T) */public void update (T entity) {getSession (). update (entity);}/* (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # delete (java. lang. long) */public void delete (Long id) {if (id! = Null) {Object entity = getById (id); if (entity! = Null) {getSession (). delete (entity) ;}}/ * (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # getByIds (java. lang. long []) */public List
            
             
GetByIds (Long [] ids) {if (ids = null | ids. length = 0) {return Collections. EMPTY_LIST;} return getSession (). createQuery (// "from" + clazz. getSimpleName () + "where id in (: ids )")//. setParameterList ("ids", ids )//. list ();}/* (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # findAll () */public List
             
               FindAll () {return getSession (). createQuery (// "from" + clazz. getSimpleName ())//. list ();}/* (non-Javadoc) * @ see com. liang. ssh2.base. baseDao # getPage (long, java. lang. long, com. liang. ssh2.util. queryHelper) */public Page getPage (long currentPage, Long pageSize, QueryHelper queryHelper) {// if you do not specify pageSize dynamically, read the configuration file if (pageSize = null) {pageSize = Configuration. getPageSize ();} // obtain the parameter List
              Parameters = queryHelper. getParameters (); Query query = getSession (). createQuery (queryHelper. getQueryListHql (); if (parameters! = Null & other meters. size ()> 0) {for (int I = 0; I <parameters. size (); I ++) {query. setParameter (I, parameters. get (I) ;}} query. setFirstResult (int) (currentPage-1) * pageSize); query. setMaxResults (pageSize. intValue (); List recordList = query. list (); // query the total number of records query = getSession (). createQuery (queryHelper. getQueryCountHql (); // note the space! If (parameters! = Null & parameters. size ()> 0) {// set the parameter for (int I = 0; I <parameters. size (); I ++) {query. setParameter (I, parameters. get (I) ;}} Long recordCount = (Long) query. uniqueResult (); // query return new Page (currentPage, pageSize, recordCount, recordList );}}
package com.liang.ssh2.service.impl;import org.springframework.stereotype.Service;import com.liang.ssh2.base.BaseDaoImpl;import com.liang.ssh2.entity.User;@Servicepublic class UserServiceImpl extends BaseDaoImpl
                
                 {}
                

It's not easy to steal a slot and write fewer interfaces !!!!!










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.