In the SSH integration development, many different DAO layers are created to crud the data in the database, in fact, each method used is almost the same, but the type of parameter is different. We can draw out a Basedao class. Due to the high cohesion and low coupling idea in development, So define as an interface, and then create the implementation class inheritance. Defines the generic type of the delivery type on the interface, which is obtained through the reflection technique and the methods in the class.
Package cn.itcast.util;
Import Java.lang.reflect.ParameterizedType;
Import Java.lang.reflect.Type;
Import java.util.List;
Import Org.springframework.orm.hibernate5.support.HibernateDaoSupport;
public class Basedaoimpl<t> extends Hibernatedaosupport implements basedao<t> {
Define a member variable so that the following method uses the
Private Class Clazz;
Public Basedaoimpl () {
Use the GetClass () method in the object class to get the class object for the current run
Class C = This.getclass ();
Gets the parameterized type of the parent class of the currently running class
Type Getgenericsuperclass ()
Returns the type of the direct superclass that represents the entity (class, interface, base type, or void) represented by this class.
Type type = C.getgenericsuperclass ();
Parameterizedtype is a subclass of type, converting type to Parameterizedtype type
Parameterizedtype ptype = (parameterizedtype) type;
Type[] Getactualtypearguments ()
Returns an array of type objects that represent the actual type parameters of this type.
type[] t = ptype.getactualtypearguments ();
Get actual type parameters
This.clazz = (Class) t[0];
System.out.println (clazz);//--->class cn.itcast.entity.CusVisit full class name
}
@Override
public void Save (T t) {
Call a method in Hibernatetemplate modeled
This.gethibernatetemplate (). Save (t);
}
@Override
public void update (T t) {
This.gethibernatetemplate (). Update (t);
}
@Override
public void Delete (T t) {
This.gethibernatetemplate (). Delete (t);
}
@Override
Public T get (int id) {
T t = (t) this.gethibernatetemplate (). Get (Clazz, id);
return t;
}
@Override
Public list<t> List () {
String Getsimplename ()
Returns the short name of the underlying class given in the source code
String hql = "from" +clazz.getsimplename ();//-->cusvisit (class name)
list<t> list = (list<t>) this.gethibernatetemplate (). Find (HQL);
return list;
}
}
This article is from the "11768969" blog, please be sure to keep this source http://11778969.blog.51cto.com/11768969/1827746
Extraction of Basedao