"Hibernate" first, Hibernate framework introduction and Getting Started program sample

Source: Internet
Author: User
Tags generator stub unique id uuid log4j
introduction of Hibernate framework

Hibernate is a further encapsulation of JDBC. One of its main starting points is the desire to simplify the programming of Java object persistence. Because the direct use of JDBC requires programmers to write a lot of complex code.

Hibernate is an open source ORM (Object-relational mapping) framework, which is a mapping between Pojo (normal Java objects) and relational databases, mapping the fields of relational databases to the properties of Java objects in memory. This way, when the programmer is working on the database, it can complete the operation of the database without having to write complex SQL statements.

The hibernate framework is a persistent layer framework that is useful for persisting Java objects into a database.
Hibernate does not require programmers to map Pojo one by one to a database table, to have multiple tables for one pojo, or to persist multiple Pojo to a single table. Ii. Core components of the Hibernate framework Configuration class: It is used to read Hibernate configuration files and generate Sessionfactory objects. The hibernate configuration file has a global configuration file (Hibernate.properties or Hibernate.cfg.xml) and a mapping file (*.hbm.xml). Sessionfactory interface: Used to generate session objects. Session interface: Used to manipulate Pojo. Query interface: Used for querying operations on Pojo. Transaction interface: Used to manage hibernate transactions.

In fact, just start to hibernate of these core components of the face cooked on the line, because since it is the core components, the future must often use. third, the hibernate of the operation process

The diagram above is the hibernate process. The general process is: The configuration class read the configuration file, including database user name, password, etc.

Sessionfactory generate Session object, you can use the Session object to generate transaction object for transaction operations, you can also use the Session object to generate query objects, perform query operations, in fact, there are criteria to perform query operations.

The words of the things said more than the effect is limited, anyway, at least to hibernate have a general understanding of it, then the detailed introduction of the code. Iv. Examples of HelloWorld entry procedures 4.1 steps: Decide what pojo you need to persist, write hibernate XML mapping file for each pojo that needs to be persisted (or use the XML mapping file for this time), and introduce hibernate dependencies in Pom.xml; Write hibernate XML configuration files, configure database user names, passwords, and the mapping files written in step 2nd; Use the schema Export tool to export the DDL (statements that create the database) to create the database, and to create the Hibernate configuration object in the Java application. This object loads the XML configuration file, creates a Sessionfactory object from the configuration object in the Java application, and obtains the session object from Sessionfactory. Used to write database access logic for an application (add-hack check). 4.2 Follow the steps above to write code:

1. Write Pojo (Message.java) that need to be persisted

Package com.zcx.entity;
Import java.util.Date;
public class Message {
    private String ID;
    Private String msg;
    Private Date createtime;
    Private Date expiretime;

    Public message () {
        super ();
    }

    Public message (string ID, String msg, date createtime, date expiretime) {
        super ();
        This.id = ID;
        this.msg = msg;
        This.createtime = Createtime;
        This.expiretime = Expiretime;
    }

    Get method and set method are omitted

2. Write mapping file for message Class (Message.hbm.xml)

<?xml version= "1.0"?>  
<! DOCTYPE hibernate-mapping public   
    "-//hibernate/hibernate mapping DTD 3.0//en"  
    "http:// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">  

Generator class = "uuid" means that using the network card information automatically generates a unique ID, each time different. This is automatically generated by setting the Generator property to the UUID. There are also 7 kinds of class:identity (for MySQL database, increment), sequence (for Oracle database), Native (used across databases, generated by the underlying dialect), Hilo (via high status composite ID), Sequencehilo, assigned (user-defined ID), foreign (external reference).

3, the use of MAVEN management dependencies, Pom.xml as follows

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < Modelversion>4.0.0</modelversion> <groupId>com.zcx.tools</groupId> <artifactId> txt2xls</artifactid> <version>0.0.1-SNAPSHOT</version> <build/> <dependencies>
        ;d ependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> <type>pom</type> </dependency> <!--https://m vnrepository.com/artifact/log4j/log4j--> <dependency> <groupId>log4j</groupId> <artifacti D>log4j</artifactid> <version>1.2.15</version> </dependency> <!--Https://mvnreposi TORY.COM/ARTIFACT/ORG.SLF4J/SLF4J-LOG4J12--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> &LT;VERSION&G 
         t;1.7.12</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> &LT;/DEPENDENCY&G
    T <dependency> <groupId>mysql</groupId> &LT;ARTIFACTID&GT;MYSQL-CONNECTOR-JAVA&LT;/ARTIFAC Tid> <version>5.1.27</version> </dependency> <!--Hibernate configuration--> < Dependency> <groupId>org.hibernate</groupId> <artifactid>hibernate-core</artifacti d> <version>3.6.5.Final</version> </dependency> <dependency> <groupi D>javassist</groupid> <artifactId>javassist</artifactId> <version>3.12.0.GA<
    /version></dependency> <dependency> <groupId>antlr</groupId> <artifactid>antlr&lt ;/artifactid> <version>2.7.6</version> </dependency> <dependency> <g Roupid>commons-collections</groupid> <artifactId>commons-collections</artifactId> ;version>3.1</version> </dependency> <dependency> <groupid>dom4j</groupid&gt
        ; <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <de
        Pendency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency> <dependency> <groupid>org.slf4j&lt ;/groupid> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> < /dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactid>hibern ate-jpa-2.0-api</artifactid> <version>1.0.0.Final</version> </dependency> </depen Dencies> </project>

4, write Hibernate configuration file, Hibernate.cfg.xml

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

Hibernate.dialect translation is a dialect, you must choose a dialect, because although most database platforms accept a common SQL subset, but there are inconsistencies between the various databases and special extensions, so when creating and querying a database, hibernate to use the dialect class you specify To manipulate the database. If you want to use Genericdialect (Common dialect Class), then hibernate can only use a common SQL subset to manipulate the database, you can not take advantage of database-specific operations.

Hibernate will look for a configuration file in the Classpath, and if you put this profile somewhere else, hibernate will not be able to find it, and you can specify the path to the profile in the configuration constructor.

5. Export DDL for creating database tables

Package com.zcx.entity;

Import org.hibernate.cfg.Configuration;
Import Org.hibernate.tool.hbm2ddl.SchemaExport;

public class Exportddl {

    /**
     * @param args */public
    static void Main (string[] args) {
        //TODO Auto-ge nerated method Stub
        Configuration cfg = new Configuration (). Configure ();
        Schemaexport export = new Schemaexport (CFG);
        Export.create (True, true);
    }


After running, the DDL is generated on the console as follows:

drop table if exists message
CREATE TABLE message (ID varchar (255) is not NULL, MSG varchar (255), Createtime date, expire Time date, primary key (ID))

The code that creates the message table can be put into the database to execute, creating the message table.
7, write the application code

Package com.zcx.entity;
Import org.hibernate.Session;
Import org.hibernate.SessionFactory;
Import org.hibernate.cfg.Configuration;

public class Test {

    /**
     * @param args */public
    static void Main (string[] args) {
        //TODO Auto-generat Ed Method stub
        Sessionfactory factory = new Configuration (). Configure (). Buildsessionfactory ();
        Session session = Factory.opensession ();
        Session.begintransaction ();
        msg = new Message ();
        Msg.setmsg ("Hello Hibernate");
        Session.save (msg);
        Session.gettransaction (). commit ();
        Session.close ();
    }

The object msg is persisted to the database after it is run, where only the MSG attribute is set for the object, the ID property is automatically generated according to the UUID algorithm, and the other two are empty.

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.