Basic Database Operations and related APIs through Hibernate

Source: Internet
Author: User

Basic Database Operations and related APIs through Hibernate

The configuration process is omitted.

Public class HibernateUtils. java for database connection

 

Package test. hibernate. dao; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. cfg. configuration; public class HibernateUtils {private static SessionFactory sessionFactory; static {// Configuration configuration = new Configuration (); // configuration. configure (); // read the default file hibernate. cfg. xml // configuration. configure (hibernate. cfg. xml); read the specified file // sessionFactory = configuration. buildSessionFactory (); sessionFactory = new Configuration ()//. configure ()//. buildSessionFactory ();}/** get a globally unique SessionFactory ** @ return */public static SessionFactory getSessionFactory () {return sessionFactory ;} /** open a Session from global SessionFactory */public static Session openSession () {return sessionFactory. openSession ();} public static void setSessionFactory (SessionFactory sessionFactory) {HibernateUtils. sessionFactory = sessionFactory ;}}

 

QueryResult. java

 

package test.hibernate.dao;import java.util.List;public class QueryResult {private int count;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;}}
Business implementation class UserDao. java
Package test. hibernate. dao; import java. util. list; import org. hibernate. criteria; import org. hibernate. query; import org. hibernate. session; import org. hibernate. transaction; import org. hibernate. criterion. order; import org. hibernate. criterion. restrictions; import test. hibernate. domain. user;/*** @ author LinDL **/public class UserDao {public void save (User user) {Session session = HibernateUtils. openSession (); Transaction transaction = null; try {transaction = session. beginTransaction (); session. save (user); transaction. commit ();} catch (RuntimeException e) {// TODO: handle exceptiontransaction. rollback (); throw e;} finally {} session. close ();} public void update (User user) {Session session = HibernateUtils. openSession (); Transaction transaction = null; try {transaction = session. beginTransaction (); session. update (user); transaction. commit ();} catch (RuntimeException e) {// TODO: handle exceptiontransaction. rollback (); throw e;} finally {} session. close ();} public void delete (int id) {Session session = HibernateUtils. openSession (); Transaction transaction = null; try {transaction = session. beginTransaction (); User user User = (User) session. get (User. class, id); // obtain the object session first. delete (user); // delete the Object transaction. commit ();} catch (RuntimeException e) {// TODO: handle exceptiontransaction. rollback (); throw e;} finally {} session. close ();}/*** @ param id * @ return */public User getById (int id) {Session session = HibernateUtils. openSession (); Transaction transaction = null; try {transaction = session. beginTransaction (); User user User = (User) session. get (User. class, id); transaction. commit (); return user;} catch (RuntimeException e) {// TODO: handle exceptiontransaction. rollback (); throw e;} finally {session. close () ;}/ ***** @ return */public List
 
  
FindAll () {Session session = HibernateUtils. openSession (); Transaction transaction = null; try {transaction = session. beginTransaction (); // use HQL to query // List
  
   
All = session. createQuery (from User ). list (); // use the object-oriented method to query Criteria criteria = session. createCriteria (User. class); // criteria. add (Restrictions. eq (id, 5); // Add a condition to query records whose id is 5. // criteria. add (Restrictions. ge (id, 6); // query records whose IDs are greater than or equal to 6. If the table is less than, the le Table is less than or equal to // criteria. addOrder (Order. asc (id); // Add a List of sorting Conditions
   
    
All = criteria. list (); transaction. commit (); return all;} catch (RuntimeException e) {// TODO: handle exceptiontransaction. rollback (); throw e;} finally {session. close () ;}/ *** @ param firstResult * @ param maxResult * @ return */@ SuppressWarnings (unchecked) public QueryResult findAll (int firstResult, int maxResult) {Session session = HibernateUtils. openSession (); Transaction transaction = null; try {transaction = session. beginTransaction (); // use HQL to Query // query Query = (Query) session. createQuery (from User); // query. setFirstResult (firstResult); // query. setMaxResults (maxResult); // List
    
     
All = query. list (); List
     
      
All = 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 (); transaction. commit (); return new QueryResult (count. intValue (), all);} catch (RuntimeException e) {// TODO: handle exceptiontransaction. rollback (); throw e;} finally {session. close ();}}}
     
    
   
  
 
Test class

 

Package test. hibernate. dao; import static org. junit. assert. *; import java. util. list; import org. junit. after; import org. junit. before; import org. junit. test; import test. hibernate. domain. user; public class UserDaoTest {UserDao userDao = new UserDao (); @ Testpublic void testSave () {User user = new User (); // user. setName (zhangsan); // userDao. save (user); for (int I = 1; I <30; I ++) {user. setId (I); user. setName (test + I); userDao. save (user) ;}@ Testpublic void testUpdate () {User user = userDao. getById (2); user. setName (history); userDao. update (user) ;}@ Testpublic void testDelete () {userDao. delete (2) ;}@ Testpublic void testGetById () {User user = userDao. getById (1); System. out. println (user) ;}@ Testpublic void testFindAll () {List
 
  
List = userDao. findAll (); for (User user: list) {System. out. println (user) ;}@ Testpublic void testFindAllIntInt () {// QueryResult queryResult = userDao. findAll (0, 10); // QueryResult queryResult = userDao. findAll (10, 10); QueryResult queryResult = userDao. findAll (20, 10); System. out. println (total number of records + queryResult. getCount (); for (Object user: queryResult. getList () {System. out. println (user );}}}
 

ConfigurationConfiguration
Configure ()
Configure (String resource)
AddResource (String resource) imports a ing file at a specified position
AddClass (Class clazz) imports a ing file with the Class name prefix and suffix. hbm. xml in the same package as the specified Class.
BuildSessionFactory ()

SessionFactorySession Factory
OpenSession ()
GetCurrentSession ()
Close ()

SessionAn important object
Operation object Method
Save (Object)
Update (Object)
Delete (Object)
Query Method
CreateQuery (String) --> Query
CreateCriteria (Class)
How to manage transactions
BeginTransaction () --> Transaction
GetTransaction () --> Transaction get the Transaction object associated with the current Session
Other methods
...

TransactionTransactions
Commit ()
Rollback ()

QueryQuery
List () queries a result set.
UniqueResult () queries a unique result. If there is no result, null is returned. If there are multiple results, an exception is thrown.
...

 

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.