1.basedao<t>
Package Org.hzy.dao;
Import Java.lang.reflect.ParameterizedType;
Import Java.lang.reflect.Type;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.cfg.Configuration; The public class Basedao<t extends entityssuper> {//parameter can be multiple <T,K> static Configuration config = new Configuratio
N (). Configure ();
static sessionfactory FAC = Config.buildsessionfactory ();
Private Class Entityclass;
Public Sessions GetSession () {return fac.getcurrentsession (); Public Basedao () {//TODO auto-generated constructor stub this.entityclass = GetParameterizedType (This.getclass ()
);
Protected class GetParameterizedType (class Clazz) {//returns the type of the direct superclass that represents the entity (class, interface, base type, or void) represented by this class.
Type ty = Clazz.getgenericsuperclass ();
Gets the parent type of the incoming class//basedao<dept>--org.hzy.dao.basedao<org.hzy.entity.dept>//System.out.println (Ty);
Type[] Types=null; if (Ty instanceof parameterizedtype) {//Note here Ty must be a generic parameter to get the current type of generic <dept>--Class Org.hzy.entity.Dept types= ((parameterizedtype) Ty). Getactualtypearguments ();
}else{try {throw new Exception ("not find parameterizedtype!");
catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
}//System.out.println (Types[0]);
Type t= ((parameterizedtype) Ty). Getrawtype ()//Gets a declaration of this type of class or interface return (Class) types[0];
Public T-Get_object (Integer ID) {return (T) this.getsession (). Get (Entityclass, id);
}
}
2. Test and return the type of your class through different classes:
public class Deptimpl extends basedao<dept>{public
static void Main (string[] args) {
Deptimpl de=new depti MPL ();
Transaction t=de.getsession (). BeginTransaction ();
System.out.println (de.get_object);
T.commit ();
}
public class Empimpl extends basedao<emp>{public
static void Main (string[] args) {
Empimpl em=new Empimpl ( );
Transaction t=em.getsession (). BeginTransaction ();
EMP Emp=em.get_object (7369);
System.out.println (Emp.getename ());
T.commit ();
}
By using generic T to reduce the redundant code for DAO, when T inherits an object (T extends Entitydao) limits the parameter type must inherit the object (Entitydao), and CLASST must have a generic parameter (Deptdaoimpl extends classt<dept>), otherwise the conversion failed.