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 Operations 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 Unique objects
* @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 ();
}
}
/** to get paged 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 ();
}
}
}
Hibernate single-table type data processing generic class