Hibernate Getting Started case

Source: Internet
Author: User

1.Hibernate Framework Overview

Hibernate's core components
In Java Web applications based on MVC design patterns, hibernate can be used as the model layer/data access layer. It maps a Java object or PO (persistent object, persisted object) to a database in a database through a configuration file (Hibernate.properties or Hibernate.cfg.xml) and a mapping file (***.hbm.xml) , and then through the operation of PO, the data in the table to increase, delete, change, check and other operations.
In addition to configuration files, mapping files, and persistence classes, the core components of hibernate include the following sections:
A) configuration class: Used to read Hibernate configuration files and generate Sessionfactory objects.
b) Sessionfactory interface: Generates session instance factory.
c) Session interface: used to operate PO. It has methods such as get (), load (), save (), update (), and delete () to load, save, update, and delete the PO. It is the core interface of hibernate.
d) query interface: Used for querying the PO. It can be generated from the CreateQuery () method of the session.
e) Transaction interface: Used to manage hibernate transactions, its main methods are commit () and rollback (), which can be generated from the session's Begintrancation () method.

Persistent Object
Persistent objects can be normal JavaBeans, and the only special thing is that they are associated with (just one) session. There are three states of JavaBeans in Hibernate:
1. Temporary status (transient): When an JavaBean object is orphaned in memory and does not have any association with the data in the database, the JavaBeans object is called a temporary object (transient object).
2. Persistent State (persistent): When a JavaBean object is associated with a session, it becomes persisted (persistent object)
3. Off-State (detached): When the session is closed, the object is also detached from the persistence state and becomes a de-detached object, which can be used freely by any layer of the application, such as data objects that can do business with the presentation layer ( Data Transfer Object).

Hibernate's Running Process
Hibernate is run as follows:
A: The application first calls the Configration class, which reads the information from the Hibernate configuration file and the mapping file and uses this information to generate a Sessionfactpry object.
B: Then a Session object is generated from the Sessionfactory object, and the transaction object is generated with the session object; Get (), load (), save (), update (), delete () and Saveorupdate () and other methods to load, save, update, delete, and other operations; In the case of a query, a query object can be generated from the session object and then executed with the Queries object, and if there is no exception, The transaction object submits the results of these operations to the database.

Hibernate runs as follows:

2. Introductory case

01. Prepare a variety of jar bags (I don't think I can teach it)

02. Prepare Student entity classes (for working with the corresponding database)

Package cn.zhang.entity;//entity classes public class Student {private int stuno;        Private String Stuname;        private int stuage;        private int stuid;    private int stuseat;        Public Student () {super ();        TODO auto-generated Constructor stub} public Student (String stuname, int stuage, int stuid, int stuseat) {        Super ();        This.stuname = Stuname;        This.stuage = Stuage;        This.stuid = Stuid;    This.stuseat = Stuseat;        } public Student (int Stuno, String stuname, int stuage, int stuid, int stuseat) {super ();        This.stuno = Stuno;        This.stuname = Stuname;        This.stuage = Stuage;        This.stuid = Stuid;    This.stuseat = Stuseat;    } public int Getstuid () {return stuid;    } public void Setstuid (int stuid) {this.stuid = Stuid;    } public int getstuseat () {return stuseat;    } public void Setstuseat (int stuseat) {this.stuseat = Stuseat; }   public int Getstuno () {return stuno;    } public void Setstuno (int stuno) {This.stuno = Stuno;    } public String Getstuname () {return stuname;    } public void Setstuname (String stuname) {this.stuname = Stuname;    } public int Getstuage () {return stuage;    } public void Setstuage (int stuage) {this.stuage = Stuage; }            }

03. Design Hibernate configuration file under src hibernate.cfg.xml

<?xml version= ' 1.0 ' encoding= ' utf-8 '? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://www.hibern Ate.org/dtd/hibernate-configuration-3.0.dtd ">

04. Design the mapping file under the entity class Student.hbm.xml (used in configuration file hibernate.cfg.xml)

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

05. Add a Test class

001. Update (ADD) a student record

Package cn.zhang.test;//adds a new data import Org.hibernate.sessionfactory;import Org.hibernate.transaction;import Org.hibernate.cfg.configuration;import Org.hibernate.classic.session;import Cn.zhang.entity.student;public Class inserttest {public        static void Main (string[] args) {        //Prepare object        Student student=new Student ("Light coat", 12,112333,2) //student.hbm.xml has been configured to increment, so there is no need to add a number here         //Read the large configuration file, get the database information to connect the configuration        configuration=new Configuration (). Configure ();         Create Sessionfactory        Sessionfactory factory = Configuration.buildsessionfactory ();        Processing session session        Opensession = Factory.opensession ();                Transaction BeginTransaction = Opensession.begintransaction ();        Opensession.save (student);                Begintransaction.commit ();                SYSTEM.OUT.PRINTLN ("Success");}    }

002. Modify a student's information

Package Cn.zhang.test;import Org.hibernate.sessionfactory;import Org.hibernate.transaction;import Org.hibernate.cfg.configuration;import Org.hibernate.classic.session;import Cn.zhang.entity.student;public Class updatetest {    /**     * @param args     *    /public static void main (string[] args) {        //1. Read the large configuration file to get the database information to connect to        Configuration Conf=new configuration (). Configure ();        2. Create Sessionfactory        sessionfactory factory =conf.buildsessionfactory ();        3 Processing Session Session Session        = Factory.opensession ();        Transaction tx=session.begintransaction ();        Get Object        Student stu =new Student (1, "Light coat", 12,112333,2);        Update        session.update (stu);        Commit TRANSACTION        tx.commit ();        SYSTEM.OUT.PRINTLN ("Update succeeded");}    }

003. Delete a specified student information

Package Cn.zhang.test;import Org.hibernate.sessionfactory;import Org.hibernate.transaction;import Org.hibernate.cfg.configuration;import Org.hibernate.classic.session;import Cn.zhang.entity.student;public Class deletetest {public        static void Main (string[] args) {        //1. Read the large configuration file to get the database information to connect to the        configuration conf=new Configuration (). Configure ();        2. Create Sessionfactory        sessionfactory factory =conf.buildsessionfactory ();        3. Processing session Session Session        = Factory.opensession ();                Transaction tx=session.begintransaction ();        Get Object        Student stu =new Student ();        Stu.setstuno (3);//Specifies the number to be deleted        //deletes the specified        session.delete (stu);        Commit TRANSACTION        tx.commit ();        System.out.println ("delete succeeded");}    }

004. Query for a specific student information

Package Cn.zhang.test;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;import Org.hibernate.classic.session;import Cn.zhang.entity.student;public class Selecttest {public    static void main ( String[] args) {        //1. Read the large configuration file to get the database information to connect to the configuration        conf=new configuration (). Configure ();        2. Create Sessionfactory        sessionfactory factory =conf.buildsessionfactory ();        3. Open session Session Session        = Factory.opensession ();        4. Load data operation           //If the table does not have a primary key column that you specify, the Get () method is null        Student Student = (Student) session.get (Student.class, 4);            If the table does not have a primary key column that you specify, the program runs to Student.getstuname () and throws an exception       //student Student = (Student) session.load (Student.class, 4);        5. Output Data        System.out.println (Student.getstuname ());        6. Close Session        Session.close ();                    }}

Hibernate Getting Started case

Related Article

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.