[Java]
In the previous blogs, we briefly described how hibernate performs CRUD.
In this article, we will take a look at these operations separately: The purpose is to summarize and back up them, please refer to the Code:
I. design the HibernateUtils class for obtaining the session
Public class HibernateUtils {
Private static SessionFactory sf;
Private static Session s;
// Load the static design mode during initialization
Static {
Configuration con = new Configuration ();
Con. configure ();
Sf = con. buildSessionFactory ();
}
// Method for obtaining objects
Public static Session getS (){
S = sf. openSession ();
Return s;
}
}
2. Use the interfaces provided by hibernate to perform CRUD operations:
Private static Session s = HibernateUtils. getS ();
Private List <User> list;
// The Object-Oriented Query Method QueryByCriteria
Public List <User> QueryByCriteria (){
Criteria c = s. createCriteria (User. class );
C. add (Restrictions. eq ("name", "zhanglei "));
List = c. list ();
Return list;
}
// Hql Query Method
Public List <User> QueryByHql (){
String hql = "from User where name =? ";
Query q = s. createQuery (hql );
Q. setString (0, "zhanglei ");
List = q. list ();
Return list;
}
// Query the wildcard
Public List <User> QueryByTongPei (){
String tongpei = "from User where name =: m ";
Query q = s. createQuery (tongpei );
Q. setString ("m", "zhanglei ");
List = q. list ();
Return list;
}
Www.2cto.com
// Method for adding a user
Public void UserAdd (){
Transaction tx = s. beginTransaction ();
User user = new User ();
User. setName ("zhanglei ");
User. setPass ("pass ");
S. save (user );
Tx. commit ();
}
// Method for deleting a user
Public void UserDelete (){
Transaction tx = s. beginTransaction ();
User user = (User) s. get (User. class, 1 );
S. delete (user );
Tx. commit ();
}
// Update the user's Method
Public void UserUpdate (){
Transaction tx = s. beginTransaction ();
User user = (User) s. get (User. class, 12 );
User. setName ("zhanglong ");
S. update (user );
Tx. commit ();
}
Supplement:
Paging set method:
Q. setFirstResult (currentPage );
Q. setMaxResults (pagesize );
Author: zhang6622056