Hibernate_2 _ add, delete, modify, and query templates:
Add, delete, modify, and query templates:
// Call the encapsulation class to generate a sessionSession session = HibernateUtils. getSession (); Transaction tx = null; // declare a Transaction try {tx = session. beginTransaction (); // start the transaction/*** place the add, delete, modify, and query Code */tx. commit (); // commit transaction} catch (RuntimeException e) {If (tx! = Null) {tx. rollback (); // rollback} throw e; // throw an exception} finally {session. close (); // release resources}
(User is the class object to be operated)
1> saved code: session. save (user );
2> updated code: session. update (user );
3> delete Code: session. delete (user );
4> Search for a data code
User user = (User) session.get(User.class, id); tx.commit(); return user;
5> query all data:
List
list = session.createQuery("FROM User").list(); tx.commit(); return List;
The return type is List. .
6> query all by page:
Query all by PAGE: List
List = session. createQuery ("From User ")//. setFirstResult (firstResult )//. setMaxResults (maxResult )//. list (); // query the total number of records Long count = (Long) session. createQuery ("select count (*) FROM User ")//. uniqueResult (); tx. commit (); // return result return new QueryResult (count. intValue (), list );
The return type is QueryResult:
Public class QueryResult {private int count; // total record private List
List; // public QueryResult (int count, List
List) {this. count = count; this. list = list;} public int getCount () {return count;} public void setCount (int count) {this. count = count;} public List
GetList () {return list;} public void setList (List
List) {this. list = list ;}}