25th Day Lazy projection on the use of warm Yang-hibernate on JDBC (iv)

Source: Internet
Author: User
Tags sessions

June 4, sunny day. " Sunny day warm air, green shade when the grass wins flowers." "

"Tao" is the experience of a special cosmic existence that only the Chinese can understand and diligently pursue. Only Chinese in the world can explain the whole meaning of Tao. However, the so-called interpretation, not the definition, more or feel. "Tao" in the " nothingness ", but also beyond the " nothingness ", the Chinese culture is the most common but the most mysterious realm.

Laotse that: Tao is the noumenon of the universe, which is the ancestor of all things in the universe.

the foreigner thinks: Tao is the source of all programs.

in programming, the Tao is narrowly turned into a DAO pattern-intended to further separate the code of the presentation layer from the business logic layer.
The general practice is: the design of a DAO interface, data insertion, modification, deletion, query and other operations are carried out in this, is the implementation of a specific transaction interface. Design a DAO interface implementation class, generally call it daoimp, it is the operation of the data to materialize.
Here is a comprehensive example of using the DAO interface to complete the Add, delete, change, and search with hibernate.

1. Build Java EE Project ( using hibernate 3.6.10)

jar package Download and import, see 19th Day lazy projection on the use of warm Yang-hibernate on jdbc (i)

2. Create MySQL database

database table creation, see 19th Day lazy projection of the use of warm Yang-hibernate on jdbc (i)

3. Creating DAO Interface Userinfodao.java

Package Edu.eurasia.dao;import Edu.eurasia.model.userinfo;public interface Userinfodao {public void Save (UserInfo userinfo);p ublic void Update (userinfo userinfo);p ublic void Delete (UserInfo userinfo);p ublic void Get (int id);p ublic void Load (int id);p ublic void Queryall (String hql);}
4. Create a DAO implementation class Userinfodaoimpl.java

< Span style= "font-family:comic Sans MS" >

Package Edu.eurasia.dao.implment;import Java.util.list;import Org.hibernate.hibernateexception;import Org.hibernate.session;import Org.hibernate.transaction;import Edu.eurasia.dao.userinfodao;import Edu.eurasia.model.userinfo;import Edu.eurasia.utils.hibernateutil;public class Userinfodaoimpl implements Userinfodao {@Overridepublic void Save (UserInfo UserInfo) {Session session = Hibernateutil.getsession (); Transaction tx = null;try {//start transaction tx = Session.begintransaction (); System.out.println ("Start adding data to Database ...");//Save data to Database Session.save (userinfo);//End Transaction Tx.commit (); tx = NULL; System.out.println ("Congratulations, the first add program runs successfully! ");} catch (Hibernateexception e) {e.printstacktrace (); if (tx! = null) {Tx.rollback ();}} finally {Hibernateutil.close ( session);}} @Overridepublic void Update (UserInfo UserInfo) {Session session = Hibernateutil.getsession (); Transaction tx = null;try {//start transaction tx = Session.begintransaction (); System.out.println ("Start updating data ...");//Save data to Database Session.update (userinfo);//End Transaction Tx.commit (); tx = NULL; System.Out.println ("Congratulations, the first update runs successfully! ");} catch (Hibernateexception e) {e.printstacktrace (); if (tx! = null) {Tx.rollback ();}} finally {Hibernateutil.close ( session);}} @Overridepublic void Delete (UserInfo UserInfo) {Session session = Hibernateutil.getsession (); Transaction tx = null;try {//start transaction tx = Session.begintransaction (); System.out.println ("Start deleting data ...");//Save data to Database Session.delete (userinfo);//End Transaction Tx.commit (); tx = NULL; System.out.println ("Congratulations, the first removal program runs successfully! ");} catch (Hibernateexception e) {e.printstacktrace (); if (tx! = null) {Tx.rollback ();}} finally {Hibernateutil.close ( session);}} @Overridepublic void Get (int id) {Session session = Hibernateutil.getsession (); System.out.println ("Start using get query data ...");//Save data to database UserInfo UserInfo = (userinfo) session.get (Userinfo.class, id); if ( UserInfo! = null) {System.out.println ("UserId:" + userinfo.getid () + "Username:" + userinfo.getusername () + "Password:" + Userinfo.getpassword ());} else {SYSTEM.OUT.PRINTLN ("ID does not exist!! ");} Hibernateutil.close (session);} @OverridepubLIC void Load (int id) {Session session = Hibernateutil.getsession (); System.out.println ("Start using load to query data ...");//Save data to database UserInfo UserInfo = (userinfo) session.load (Userinfo.class, id); if ( UserInfo! = null) {System.out.println ("UserId:" + userinfo.getid () + "Username:" + userinfo.getusername () + "Password:" + Userinfo.getpassword ());} else {SYSTEM.OUT.PRINTLN ("ID does not exist!! ");} Hibernateutil.close (session);} @Overridepublic void Queryall (String hql) {Session session = Hibernateutil.getsession (); list<userinfo> users = Session.createquery (HQL). List (); for (UserInfo userinfo:users) {System.out.println ( Userinfo.getusername ());} Hibernateutil.close (session); System.out.println ("Congratulations, the first all query program runs successfully! ");}}
5. Create Pojo class UserInfo
Package Edu.eurasia.model;public class UserInfo {private int id;private string Username;private string Password;public in T GetId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;}}

6. Write Object Relational mapping file UserInfo.hbm.xml
<?xml Version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ HIBERNATE-MAPPING-3.0.DTD ">7. Add hibernate.cfg.xml configuration file

<?xml version= ' 1.0 ' encoding= ' gb2312 '? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://hibern Ate.sourceforge.net/hibernate-configuration-3.0.dtd ">8. public class files Hibernateutil.java
Package Edu.eurasia.utils;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;public class Hibernateutil {public static Session getsession () {sessionfactory Sessions = new Configuration (). Configure (). Buildsessionfactory (); Session session = Sessions.opensession (); return session;} public static void Close (Session session) {          if (Session!=null&&session.isopen ()) {              session.close ();          }      }  }
9, set up Test class Hibtest.java

Package Edi.eurasia.test;import Org.junit.test;import Edu.eurasia.dao.userinfodao;import Edu.eurasia.dao.implment.userinfodaoimpl;import Edu.eurasia.model.userinfo;public class HibTest {private Userinfodao Userinfodao = new Userinfodaoimpl (); @Testpublic void Testsave () {UserInfo UserInfo = new UserInfo (); Userinfo.setusername ("Li Keran"); Userinfo.setpassword ("123 "); Userinfodao. Save (userinfo);} @Testpublic void Testupdate () {UserInfo UserInfo = new UserInfo (); Userinfo.setid () userinfo.setusername ("Li Keran 2"); Userinfo.setpassword ("123"); Userinfodao. Update (userinfo);} @Testpublic void Testdelete () {UserInfo UserInfo = new UserInfo (); Userinfo.setid (+); Userinfodao.delete (UserInfo);} @Testpublic void Testget () {Userinfodao. Get (21);} @Testpublic void TestLoad () {Userinfodao. Load (1);} @Testpublic void Testqueryall () {//userinfodao. Queryall ("from UserInfo"); Userinfodao. Queryall ("Select u from UserInfo u");}}

10. Run test results

Select Mybatistest, right-->run as->junit Test. Note: When testing, one test, one test is the time, you can block the other several.
The Engineering chart is as follows:








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.