<span style= "FONT-SIZE:18PX;"
>package cn.itcast.oa.base;
Import Java.lang.reflect.ParameterizedType;
Import java.util.List;
Import Javax.annotation.Resource;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.criterion.Restrictions; @SuppressWarnings ("unchecked") public abstract class Basedaoimpl<t> implements basedao<t> {@Resource Priva
Te Sessionfactory sessionfactory;
protected class<t> Clazz; /** * below through reflection to get class/public Basedaoimpl () {Parameterizedtype pt = (parameterizedtype) this.getclass (). getgeneric
Superclass ();
Clazz = (class<t>) pt.getactualtypearguments () [0];
SYSTEM.OUT.PRINTLN ("---> clazz =" + Clazz);
} public void Save (T entity) {getsession (). Save (entity);
public void update (T entity) {getsession (). Update (entity);
public void Delete (Long id) {Object obj = getsession (). Get (Clazz, id);
GetSession (). Delete (obj); Public T GetByID (Long ID) {return (T) GetSession (). Get (Clazz, id);
List<t> getbyids (long[] IDs) {//from User WHERE ID in (?) Return GetSession (). CreateQuery (///[from User WHERE ID in (: IDS)]///. Setparameterlist ("IDs", IDS)///. Li
St ();
Return GetSession (). Createcriteria (Clazz)//. Add (restrictions.in ("id", IDS))//. List ();
Public list<t> FindAll () {//Return getsession (). CreateQuery ("from" + Clazz.getsimplename ()). List ();
Return GetSession (). Createcriteria (clazz). List (); /** * Get the currently available session * * @return/protected session getsession () {return Sessionfactory.getcurrentsessi
On (); }}</span>
There are two ways to get Clazz
1, Method one:
1, the Clazz is declared as a protected modifier, which can be accessed in the class.
2, the value of this property is passed in the constructor method of each subclass, such as:
Public Roledaoimpl () {clazz = Role.class;}
Public Userdaoimpl () {clazz = User.class;}
2, method Two: Using the way of reflection:
1, write the following code in the default construction method of Basedaoimpl:
Parameterizedtype pt = (parameterizedtype) this.getclass (). Getgenericsuperclass ();
Clazz = (Class) pt.getactualtypearguments () [0];
2, note: Basedaoimpl can not be used directly, can only use his subclass, otherwise this code is invalid.
Description
1, the use of generic technology, can be used more convenient, such as: User user = Userdao.getbyid (1L); No forced transitions are required
2,getbyid (Id:long) and Getbyids (ids:long[]) do not merge into a method with variable parameters,
Because that is inconvenient to use, for example, to use often to get an object from an ID is very inconvenient:
list<user> list = Userdao.getbyids (1L); User user = List.size () > 0? List.get (0): null.