Hibernate's implementation of basic database operations

Source: Internet
Author: User

The configuration process is omitted.

Common class Hibernateutils.java for database connections

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 the 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) Session.get (user.class, id);//To get the Entity object Session.delete (user) First,//delete the Entity 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) Session.get (user.class, id); Transaction.commit (); return user;} catch (RuntimeException e) {//Todo:handle exceptiontransaction.rollback (); throw e;} finally {Session.close ()}} /** * @return */public list<user> FindAll () {Session session = Hibernateutils.opensession (); Transaction Transaction = null;try {Transaction = Session.begintransaction ();//Use HQL query//list<user> all = Session. CreateQuery ("from User"). List ();//Use Object-oriented method to query criteria = SESSION.CREatecriteria (User.class);//Criteria.add (RESTRICTIONS.EQ ("id", 5);//Add a restriction, query ID equals 5 record//Criteria.add ( RESTRICTIONS.GE ("id", 6));////a record with a query ID greater than or equal to 6, the LT table is less than, the Le table is less than or equal to//Criteria.addorder (ORDER.ASC ("id"));//Add sort criteria list< user> 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 first Result, int Maxresult) {Session session = Hibernateutils.opensession (); Transaction Transaction = null;try {Transaction = Session.begintransaction ();//Use HQL query//query query = (query) session.cr Eatequery ("from User");//Query.setfirstresult (Firstresult);//Query.setmaxresults (Maxresult);//List<user> all = Query.list (); list<user> all = Session.createquery ("from User"). Setfirstresult (Firstresult)//.setmaxresults (MaxResult)//. List ();//query 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 ("Zhang San");//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<user> List = Userdao.findall (); for (user user:list) {System.out.println (user );}} @Testpublic void Testfindallintint () {//QueryResult QueryResult = userdao.findall (0);//QueryResult queryresult= Userdao.findall (10, 10); QueryResult QueryResult = Userdao.findall (20, 10); System.out. println ("Total Records" + Queryresult.getcount ()); for (Object user:queryResult.getList ()) {System.out.println (user);}}} 


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. Reprint please specify the source Http://blog.csdn.net/lindonglian

Hibernate's implementation of basic database operations

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.