Hibernate_2 _ add, delete, modify, and query templates:

Source: Internet
Author: User

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 ;}}








Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.