hibernate-Basic introduction case, adding and deleting

Source: Internet
Author: User

Project structure:

Database:

/*sqlyog Ultimate v12.09 (+ bit) mysql-5.5.53:database-hibernate01************************************************ *!40101 set NAMES UTF8 */;/*!40101 set sql_mode= ' */;/*!40014 set @[email protected]@ Unique_checks, unique_checks=0 */;/*!40014 SET @[email protected] @FOREIGN_KEY_CHECKS, foreign_key_checks=0 */;/ *!40101 set @[email protected] @SQL_MODE, sql_mode= ' No_auto_value_on_zero ' */;/*!40111 set @[email  Protected] @SQL_NOTES, sql_notes=0 */; CREATE DATABASE/*!32312 IF not exists*/' hibernate01 '/*!40100 DEFAULT CHARACTER SET UTF8 */; Use ' hibernate01 ',/*table structure for table ' customer ' */drop Table IF EXISTS ' customer '; CREATE TABLE ' customer ' (' id ' int (one) ' NOT null auto_increment, ' name ' varchar (+) Default NULL, ' age ' int (one) ' Default NULL, PRIMARY KEY (' id ')) engine=innodb auto_increment=5 DEFAULT charset=utf8;/*data for the table ' customer ' */insert i Nto ' Customer ' (' id ', ' name ', ' age ') VALUES (1, ' Zhang San ', 20), (2, ' Harry ', 22), (3, ' Zhao Liu ', 29);/*!40101 Set [Email protected]_sql_mode */;/*!40014 set [Email protected]_foreign_key_checks */;/*!40014 Set [Email protected]_unique_checks */;/*!40111 Set [email protected]_sql_notes */;

The jar package used:

1. Import Hibernate core must pack (\lib\required)

2. Import the MySQL driver package

3. Import log4j Log Package

Project Code:

Com.gordon.domain:

--customer.java

Package Com.gordon.domain;public class Customer {private Integer id;private String name;private integer age;public intege R GetId () {return ID;} public void SetId (Integer id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public Integer Getage () {return age;} public void Setage (Integer age) {this.age = age;} @Overridepublic String toString () {return "Customer [id=" + ID + ", name=" + name + ", age=" + Age + ", getId () =" + GetId (  ) + ", getName () =" + getName () + ", getage () =" + getage () + ", getclass () =" + getclass () + ", hashcode () =" + hashcode () + ", ToString () = "+ super.tostring () +"] ";}}

--customer.hbm.xml

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping public     "-//hibernate/hibernate mapping DTD 3.0//en"    "Http://www.hibernate.org/dtd /hibernate-mapping-3.0.dtd ">

*hibernate Delete/update, to first based on the ID or the corresponding field query data, in order to update or remove the data through the Update/delete method, their own construction of the object input operation will be error.

Com.gordon.test:* Test to import the JUNIT4 test package, then you can double-click on the method to select the method name, right-click runas run in JUnit.

--testhibernate.java

Package Com.gordon.test;import Java.util.list;import Org.hibernate.query;import org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.transaction;import Org.hibernate.cfg.configuration;import Org.junit.test;import Com.gordon.domain.customer;import Com.gordon.utils.hibernateutil;public class TestHibernate { /** * Stores a data */@Testpublic void Testsave () {Configuration configuration = new configuration (). Configure (); Sessionfactory sessionfactory = Configuration.buildsessionfactory (); Session session = Sessionfactory.opensession (); Transaction tr = session.begintransaction (); Customer customer = new Customer (); Customer.setname ("test"); customer.setage; try {session.save (customer); tr.commit ();} catch (Exception e) {tr.rollback (); E.printstacktrace ();} Session.close ();} /** * Delete a data */@Testpublic void Testdelete () {Configuration configuration = new configuration (). Configure (); Sessionfactory sessionfactory = Configuration.buildsessionfactory (); Session session = SESSIONFACTORY.OPensession (); Transaction tr = session.begintransaction (); Customer customer = null;try {customer = Session.get (Customer.class, 4); Session.delete (customer); Tr.commit ();} catch ( Exception e) {tr.rollback (); E.printstacktrace ();} Session.close ();} /** * Modify a data */@Testpublic void Testupdate () {Configuration configuration = new configuration (). Configure (); Sessionfactory sessionfactory = Configuration.buildsessionfactory (); Session session = Sessionfactory.opensession (); Transaction tr = session.begintransaction (); Customer customer = null;try {customer = Session.get (Customer.class, 1); Customer.setname ("Jack"); Session.update ( customer); Tr.commit ();} catch (Exception e) {tr.rollback (); E.printstacktrace ();} Session.close ();} /** * Get multiple data, query can not use transaction */@SuppressWarnings ("unchecked") @Testpublic void Testgetall () {Session session = Hibernateutil.getsession (); List<customer> customers = null;try {query query = Session.createquery ("from Customer"); customers = Query.list ();} catch (Exception e) {E.printstaCktrace ();} Session.close (); for (customer customer:customers) {System.out.println (customer);}} /** * Gets a piece of data, the query can not use the transaction */@Testpublic void Testget () {Session session = Hibernateutil.getsession (); Customer customer = null;try {customer = Session.get (Customer.class, 1);} catch (Exception e) {e.printstacktrace ();} Session.close (); SYSTEM.OUT.PRINTLN (Customer);}}

Com.gordon.utils:

--hibernate.util.java

Package Com.gordon.utils;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;public class Hibernateutil {private static final Configuration configuration;private Static final Sessionfactory sessionfactory;static {configuration = new configuration (). Configure (); Sessionfactory = Configuration.buildsessionfactory ();}; public static Session GetSession () {return sessionfactory.opensession ();}}

Hibernate.cfg.xml:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http://www.hibernate.org/ Dtd/hibernate-configuration-3.0.dtd ">

hibernate-Basic introduction case, adding and deleting

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.