Hibernate (1) Hibernate introduction and simple examples to understand hibernate transaction rollback usage

Source: Internet
Author: User
Tags commit generator naming convention rollback
1 Hibernate profileHibernate is an ORM (object relation mapping objects-relational mapping) framework that is in the project's Persistence Layer, also known as the Persistence layer framework (persistence layer framework and OJB, etc.). Hibernate is essentially a lightweight encapsulation of JDBC. 2 Benefits of using Hibernate

① introduces hibernate to refine worker roles, giving programmers more attention to business processes. Let database personnel pay more attention to the various operations related to the database.
② layering is clearer and less coupled
③ versatility: It's easier to move from one database platform to another
④: Programming Java objects with relational databases for easier operation
⑤ Performance Guarantee: Hibernate may be based on different databases, processing different operations is the most optimized SQL statements, without our thinking, for the sub-algorithm, in Hibernate will appear more simple and reliable.
⑥ Increased program Robustness 3 Some concepts and development methods

①:Three ways Hibernate is developed:
-by Domain object->mapping->db. (Official recommendation)
-Starting with DB, use tools to generate mapping and domain Object. (More use)
-Starts with the mapping file.
② data Persistence layer/Object Relational mapping File This file describes the relationship of tables and objects, and the corresponding relationship between the properties of the object and the fields of the table; naming convention : domain object name. Hbm.xml " 4 simple example

① Introducing Hibernate Development Kit (HTTP://PAN.BAIDU.COM/S/1QYWE6NY)
② Creating a data table, writing domain code
③ writing Employee.hbm.xml file (Object Relational mapping file)

<?xml version= "1.0" encoding= "Utf-8"?> <!--mapping file requires a DTD to specify format--<! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://hibernate.sourceforge.net/hi Bernate-mapping-3.0.dtd ">  

④ manual Configuration hibernate.cfg.xml file (Hibernate's core profile), which is used to configure the type of database connected, driver, user name, Password, etc. (HIBERNATE-DISTRIBUTION-3.3.1.GA-DIST\HIBERNATE-DISTRIBUTION-3.3.1.GA\PROJECT\ETC)

<?xml version= ' 1.0 ' encoding= ' utf-8 '?> <! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://hibernat
        E.sourceforge.net/hibernate-configuration-3.0.dtd ">  

⑤ Write testmain.java file, test crud

public static void Deleteemployee () {Session session = Mysessionfactory.getsessionfactory (). Opensession ();

    Transaction ts = session.begintransaction ();

    Session.delete (Session.load (Employee.class, 3));

    Ts.commit ();
Session.close ();

    } public static void UpdateEmployee () {Session session = Mysessionfactory.getsessionfactory (). Opensession ();

    Transaction ts = session.begintransaction ();

    Modify User Employee employee = (employee) session.load (Employee.class, 3);
    Employee.setname ("Hello");

    Ts.commit ();
Session.close (); } public static void AddEmployee () {///1 Creates a configuration that is used to read the Hibernate.cfg.xml file and complete initialization//configuration con
    figuration = new Configuration (). Configure ("Hibernate.cfg.xml"); Configuration configuration = new configuration (). Configure (); The default is Hibernate.cfg.xml//2 Create Sessionfactory "This is a session factory, is a heavyweight object" sessionfactory sessionfactory = Configuration.bu
    Ildsessionfactory (); 3 Create session, equivalent to JDBC ConneCtion "" Session session = Sessionfactory.opensession ();

    4 for Hibernate, a transaction is required to commit Transaction transcation = Session.begintransaction () When a crud operation is performed;
    Add an employee employee employees employee = new Employee ();
    Employee.setname ("Jiaozenglian");
    Employee.setemail ("jiao@sohu.com");

    Employee.sethiredate (New Date ()); Save Session.save (employee);
    ==> INSERT INTO ...//submit transcation.commit ();
Session.close (); }

Mysessionfactory.java file (set it as a singleton because the configuration object is resource-intensive)

Import org.hibernate.SessionFactory;
Import org.hibernate.cfg.Configuration;
Public final class Mysessionfactory {
    private static sessionfactory sessionfactory = null;
    static {
        sessionfactory = new Configuration (). Configure (). Buildsessionfactory ();
    }

    public static Sessionfactory Getsessionfactory () {
        return sessionfactory;
    }
}
5 Switching databases

① First, reconfigure the hibernate.cfg.xml file

<?xml version= ' 1.0 ' encoding= ' utf-8 '?> <! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://hibernat
        E.sourceforge.net/hibernate-configuration-3.0.dtd ">  

② configuration Employee.hbm.xml file

<?xml version= "1.0" encoding= "Utf-8"?> <!--mapping file requires a DTD to specify format--<! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://hibernate.sourceforge.net/hi Bernate-mapping-3.0.dtd ">  
6 Hibernate Fundamentals Diagram 


only the configuration is a class, the other three are interface interface.
- Other libraries required by Hibernate :
7 Optimizing UpdateEmployee Adding a transaction rollback

public static void UpdateEmployee () {
    //ROLLBACK TRANSACTION
    Session session = Mysessionfactory.getsessionfactory (). Opensession ();

    Transaction ts = null;
    try {
        ts = session.begintransaction ();
        Modify User
        Employee employee = (employee) session.load (Employee.class, 3);

        Employee.setname ("Nihao");

        Ts.commit ();

    } catch (Exception e) {
        if (ts!=null) {
            ts.rollback ();
        }
        E.printstacktrace ();
        throw new RuntimeException (E.getmessage ());
    } Finally {
        if (session!=null && session.isopen ()) {
            session.close ();}}
}

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.