Single-table data processing generic type in Hibernate and single-table in hibernate
Package chengfei. hibernate. Dao;
Import java. util. List;
Import org. hibernate. HibernateException;
Import org. hibernate. Session;
Import org. hibernate. Transaction;
Import chengfei. hibernate. tool. HibernateUtils;
/** Hibernate database operation generic classes
* @ Author Administrator
* @ Param <T>
*/
Public class service <T> {
Private Class <T> c;
Public service (Class <T> c ){
This. c = c;
}
/** Save
* @ Param t
*/
Public void save (T t ){
Session session = HibernateUtils. openSession ();
Transaction tx = null;
Try {
Tx = session. beginTransaction ();
Session. save (t );
Tx. commit ();
} Catch (HibernateException e ){
Tx. rollback ();
Throw e;
} Finally {
Session. close ();
}
}
/** Delete
* @ Param id
*/
Public void delete (Integer id ){
Session session = HibernateUtils. openSession ();
Transaction tx = null;
Try {
Tx = session. beginTransaction ();
T t = this. getById (id );
Session. delete (t );
Tx. commit ();
} Catch (HibernateException e ){
Tx. rollback ();
Throw e;
} Finally {
Session. close ();
}
}
/** Update
* @ Param t
*/
Public void update (T t ){
Session session = HibernateUtils. openSession ();
Transaction tx = null;
Try {
Tx = session. beginTransaction ();
Session. update (t );
Tx. commit ();
} Catch (HibernateException e ){
Tx. rollback ();
Throw e;
} Finally {
Session. close ();
}
}
/** Get the unique object
* @ Param id
* @ Return
*/
@ SuppressWarnings ("unchecked ")
Public T getById (Integer id ){
Session session = HibernateUtils. openSession ();
Transaction tx = null;
Try {
Tx = session. beginTransaction ();
T t = (T) session. get (c, id );
Tx. commit ();
Return t;
} Catch (HibernateException e ){
Tx. rollback ();
Throw e;
} Finally {
Session. close ();
}
}
/** Get all
* @ Return
*/
@ SuppressWarnings ("unchecked ")
Public List <T> FindAll (){
Session session = HibernateUtils. openSession ();
Transaction tx = null;
Try {
Tx = session. beginTransaction ();
List <T> list = session. createQuery ("from" + c. getSimpleName ())
. List ();
Tx. commit ();
Return list;
} Catch (HibernateException e ){
Tx. rollback ();
Throw e;
} Finally {
Session. close ();
}
}
/** Obtain paging data
* @ Param firstResult
* @ Param maxresult
* @ Return
*/
@ SuppressWarnings ({"unchecked", "rawtypes "})
Public QueryResult FindAll (int firstResult, int maxresult ){
Session session = HibernateUtils. openSession ();
Transaction tx = null;
Try {
Tx = session. beginTransaction ();
List <T> list = session. createQuery (//
"From" + c. getSimpleName ())//
. SetFirstResult (firstResult )//
. SetMaxResults (maxresult). list ();
Tx. commit ();
Long count = (Long) session. createQuery (
"Select count (*) from" + c. getSimpleName ())//
. UniqueResult ();
Return new QueryResult (list, count. intValue ());
} Catch (HibernateException e ){
Tx. rollback ();
Throw e;
} Finally {
Session. close ();
}
}
}