Wechat official account: CompassBlog

Welcome to follow, forward, learn from each other, common progress!

If you have any questions, please leave a message.

1. Hibernate framework Overview

(1) What is Hibernate

Hibernate is an open source ORM framework and one of the mainstream Java persistence layer frameworks. It provides lightweight object encapsulation for JDBC and enables Java developers to operate databases with object-oriented programming ideas.

(2) Hibernate’s position in the three-tier architecture


The Struts2 framework mentioned in the previous article replaces the Web layer of the three-layer framework, while Hibernate framework replaces the DAO layer, as described in the following figure:



(3), what is ORM ORM (Object Relational Mapping), that is, the use of metadata to describe the Mapping between objects and database tables, automatic Java applications in the Object, persistent to Relational database tables. You can manipulate database tables by manipulating Java objects. ORM can be thought of as a link between relational data and objects, and developers only need to focus on the objects mapped on one side of the link. The implementation principle of ORM is shown as follows:



(4) Advantages and functions of Hibernate framework

  • Hlbernate is a lightweight encapsulation of JDBC database access code, which greatly simplifies the tedious repetitive code in the data access layer, reduces memory consumption and speeds up operation efficiency.
  • Hlbernate is a mainstream jdbc-based persistence framework and an excellent ORM implementation, which greatly simplifies the coding work of DAO (DataAccess Object) layer. When operating a database, it can be done in an object-oriented manner, eliminating the need to write SQL statements.
  • Hlbernate has excellent performance and mapping flexibility. It supports many relational databases, from one-to-one to many-to-many complex relationships.
  • Strong scalability, because of the open source code and API open, when its own function is not enough, you can code for extension.

2. Build Hibernate framework and complete the first application instance

(1) Create a Web project and import the required JAR package, including the database driver package, as shown below:



Mysql > create database demo_project; mysql > create table user;

Create database demo_project statement:

create database demo_project;
Copy the code

Common table user statement:

CREATE TABLE `user` (
  `id` int(10) NOT NULL,
  `name` varchar(50) DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `height` int(11) DEFAULT NULL,
  `weight` double(10,0) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy the code

(3) create entity user.java as follows:

User.java

package com.hibernate.demo; Public class User {// private int id; private String name; private int age; private int height; private int weight; // Setter and getter methods public intgetId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getHeight() {
        return height;
    }
    public void setHeight(int height) {
        this.height = height;
    }
    public int getWeight() {
        return weight;
    }
    public void setWeight(int weight) { this.weight = weight; }}Copy the code

(4) Import constraints. Create an ORM configuration file user.hbm. XML under the same package as the entity to write THE ORM metadata. The specific configuration code is as follows:

User.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-mapping package="com.hibernate.domain" >

    <class name="User" table="user" >
        <id name="id"  >
            <generator class="native"></generator>
        </id>
        <property name="name" column="name" ></property>
        <property name="age" column="age" ></property>
        <property name="height" column="height" ></property>
        <property name="weight" column="weight" ></property>    
    </class>

</hibernate-mapping>
Copy the code

(5) Create the hibernate. Cfg. XML master configuration file under SRC. The specific configuration code is as follows:

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-configuration> <session-factory> <! -- Database driver --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <! -- database url --> <property name="hibernate.connection.url">jdbc:mysql:///demo_project</property> <! -- Database connection user name --> <property name="hibernate.connection.username">root</property> <! -- Database connection password --> <property name="hibernate.connection.password">root</property> <! --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="hibernate.show_sql">true</property>

        <property name="hibernate.format_sql">true</property>

        <property name="hibernate.hbm2ddl.auto">update</property> <! Orm metadata --> <mapping resource="com/hibernate/domain/User.hbm.xml" />

    </session-factory>
</hibernate-configuration>
Copy the code

(6) Create a test class testDemo. Java and write the test code as follows:

TestDemo.java

package com.hibernate.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Test; import com.hibernate.domain.User; Public class TestDemo {@test // Insert information public voidtest(){ Configuration conf = new Configuration().configure(); SessionFactory sessionFactory = conf.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); User u = new User(); u.setName("Kong Yiji"); u.setAge(22); u.setHeight(172); u.setWeight(120); session.save(u); tx.commit(); session.close(); sessionFactory.close(); }}Copy the code

(7) Running results: The information is inserted successfully. The specific results are shown as follows:





The project running environment: JDK1.7, Tomcat7.0

Hibernate configuration file details

(1) OrM metadata configuration details:

package

<! -- Package attribute: Fill in a package name. If you need to write the full class name inside the element, you can simply write the class name --> <hibernate-mapping package="com.hibernate.domain" >
Copy the code

class

<! Table: database table name --> <class name="User" table="user" >
Copy the code

id

<! Name: enter the name of the attribute corresponding to the primary key column(Optional): enter the name of the primary key column in the table. Default: Column names use attribute names by defaulttype(Optional): Enter the type of the column (attribute). Hibernate automatically detects the attribute type of the entity. Fill each type has three kinds of method: Java type | | hibernate type database type not - null (optional) : the configuration whether the attributes (columns) can't be empty. Default value:falseLength (Optional): Sets the length of columns in the database. Default: Use the maximum length of the database type --> <id name="id"> <! Generator: primary key generation policy --> < Generator class="native"></generator>
        </id>
Copy the code

property

<! -- Property element: common attribute mapping except id Name: enter the attribute name column(Optional): enter the column nametype(Optional): Enter the type of the column (attribute). Hibernate automatically detects the attribute type of the entity. Fill each type has three kinds of method: Java type | | hibernate type database type not - null (optional) : the configuration whether the attributes (columns) can't be empty. Default value:falseLength (Optional): Sets the length of columns in the database. Default: use the maximum length of the database type --> <property name="name" column="name"> <! -- <column name="cust_name" sql-type="varchar" ></column> -->
        </property>
        <property name="age" column="age" ></property>
        <property name="height" column="height" ></property>
        <property name="weight" column="weight" ></property>
Copy the code

(2) Hibernate main configuration file

Will choose configuration

<! -- Database driver --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <! -- database url --> <property name="hibernate.connection.url">jdbc:mysql:///demo_project</property> <! -- Database connection user name --> <property name="hibernate.connection.username">root</property> <! -- Database connection password --> <property name="hibernate.connection.password">root</property> <! --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
Copy the code

Optional configuration

<! --#hibernate.show_sql true 
             #hibernate.format_sql true-- > <! Print hibernate generated SQL statements to the console --> <property name="hibernate.show_sql">true</property> <! Format (syntactic indentation) the SQL statement generated by Hibernate --> <property name="hibernate.format_sql">true</property> <! --## Auto schema export automatically export table structure, automatically create table
        # hibernate.hbm2dcl. auto create Automatically creates a table. Each time the framework runs, a new table is created. The previous table will be overwritten and the table data will be lost. (Test use in development environment)
        #hibernate.hbm2ddl. Auto create-drop Creates tables automatically and drops all tables at the end of each frame run. (Test use in development environment)
        # hibernate.hbm2dcl. auto update(recommended) automatically generates tables and will not regenerate them if they already exist; Automatically update the table if it changes (without deleting any data)
        #hibernate. Hbm2ddl. Auto validate No automatic table generation, each startup will verify whether the table in the database is correct, verification failure.
         -->
        <property name="hibernate.hbm2ddl.auto">update</property>
Copy the code

Importing ORM metadata configuration

<! Write: Enter the path under SRC --> <mapping resource="com/hibernate/domain/User.hbm.xml" />
Copy the code


Follow wechat official account Compassblog and reply “Hibernate Series 1” to obtain the source code of this project



You may also like:

  • 【SSH framework 】 Struts2 series (2)

  • 【SSH framework 】 Struts2 series (1)

  • Front-end series overview of JavaScript basics

  • Front-end series overview of CSS basics

  • An overview of the HTML basics of the front-end series



This series will continue to be updated later, welcome to pay attention!


If you find this article useful, please share it with your friends!

This article can be reproduced arbitrarily, reproduced please indicate the source!


Scan the code to follow the wechat official account to learn more