Using generics to extract DAO layers, plus transaction annotation issues (Java.lang.Class cannot be cast to Java.lang.reflect.ParameterizedType)

Source: Internet
Author: User

To use generics to extract Basedao layers, there are problems in simplifying operations:

@Transactional this annotation can be inherited, so you want to write on the extracted Basedao layer, so that the implementation of the class can not write @transactional, you can open the transaction.

Problem Description:

Due to laziness, did not give Basedao suction interface, 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<t>{@Resourceprivate sessionfactory Sessionfactory; Class <T> clazz;/** * Gets the parameter type by Reflection */public Basedaoimpl () {System.out.println (this); Parameterizedtype pt = (parameterizedtype) this.getclass (). Getgenericsuperclass (); clazz= (class<t>) Pt.getactualtypearguments () [0];} /** * Gets 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) getsession (). 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<t> 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<t> 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 the user does not specify pageSize dynamically, read the configuration file if (pagesize==null) {pagesize= Configuration.getpagesize ();} Get parameter list<object> parameters = Queryhelper.getparameters (); Query query = getsession (). CreateQuery (QUERYHELPER.GETQUERYLISTHQL ()); if (Parameters!=null&¶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 = GetSession () for total number of records. CreateQuery (QUERYHELPER.GETQUERYCOUNTHQL ()); Note the space! if (Parameters! = null && parameters.size () > 0) {//Set 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 the following:

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 <user>{}

notice I put @transactional on the Basedao, because @transactional can inherit, so Userserviceimpl is not put

When you start the server, you get an error: Caused By:java.lang.ClassCastException:java.lang.Class cannot is cast to Java.lang.reflect.ParameterizedType

Why is that?

Test a half-day discovery, error on the Basedao on the note:@Transactional , the reason is not very clear!!!

Two solutions:

First, directly Basedao on the @transactional annotations, in the implementation of the class added @transactional, for this example, in Userserviceimpl plus @transactional can open the transaction, will not error!

Second, do not lazy, obediently to Basedao to smoke an interface bar, and nothing else to change, @Transactional or can still inherit, modify the code 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<t> {/** * Save entity * @param entity */public abstract void Save ( t entity);/** * Get entity based on ID * @param ID * @return */public abstract T getById (Long ID);p ublic abstract void update (T entity); public abstract void Delete (Long id);p ublic abstract list<t> getbyids (long[] IDs);p ublic abstract list<t> fin DAll ();/** *  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<t> implements basedao<t>{@ Resourceprivate sessionfactory sessionfactory; Class <T> clazz;/** * Gets the parameter type by Reflection */public Basedaoimpl () {System.out.println (this); Parameterizedtype pt = (parameterizedtype) this.getclass (). Getgenericsuperclass (); clazz= (class<t>) Pt.getactualtypearguments () [0];} /** * Gets 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) getsession (). 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<t> 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<t> 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 the user does not specify pageSize dynamically, read the configuration file if (pagesize==null ) {pagesize=configuration.getpagesize ();} Get parameter list<object> parameters = Queryhelper.getparameters (); Query query = getsession (). CreateQuery (QUERYHELPER.GETQUERYLISTHQL ()); if (Parameters!=null&¶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 = GetSession () for total number of records. CreateQuery (QUERYHELPER.GETQUERYCOUNTHQL ()); Note the space! if (Parameters! = null && parameters.size () > 0) {//Set 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);}} 

</pre><pre name= "code" class= "java" >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<user>{}

Want to steal a lazy, less write an interface, also not easy AH!!!!!










Using generics to extract DAO layers, plus transaction annotation issues (Java.lang.Class cannot be cast to Java.lang.reflect.ParameterizedType)

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.