Hibernate - Getting Started

What is Hibernate?

  1. Hibernate is a framework;
  2. Hibernate is an ORM framework (Object Relation Mapping, object relational mapping);
  3. Hibernate is in the persistence layer of the project (so it is also called the persistence layer framework); (persistence means saving the information of the object to the database or file)
  4. Hibernate is actually a lightweight encapsulation of JDBC;
  5. The basis of Hibernate is the reflection mechanism of Java.

Summary : Hibernate is an ORM framework that lightweight encapsulates JDBC and acts as the persistence layer of the project.

write picture description here

Benefits of Hibernate

  1. The introduction of Hibernate can refine the roles of workers and let programmers care more about business processes. Let database personnel pay attention to various operations related to the database;
  2. The layering is clearer and the coupling is smaller;
  3. Strong versatility: It can be more easily transferred from one database platform to other platforms;
  4. Objectification: The relational database is turned into a Java object, which is more convenient to operate;
  5. Performance guarantee: Hibernate may use optimized SQL statements for different operations according to different databases, without us thinking about it;
  6. Increased program robustness.

Quick Start Case

Hibernate can be used in J2SE projects as well as in J2EE projects. (Struts is a web layer framework and can only be used in J2EE projects)

Development process :
1. Create a project
2. Introduce the development kit of Hibernate
3. There are three ways to develop Hibernate:

(1) By Domain Object -> mapping -> db (official recommendation)

(2) Starting from DB, use tools to generate mapping and Domain Object (more used)

(3) Start with the mapping file

4. We use the second way to develop, using the MySQL database, first create the employee table

CREATE TABLE employee (
    id INT NOT NULL AUTO_INCREMENT,
    PRIMARY KEY(id),
    NAME VARCHAR (64) NOT NULL,
    email VARCHAR (64) NOT NULL,
    hiredate date NOT NULL
);

5. Develop domain objects and object relationship mapping files

Object relationship file : used to specify the mapping relationship between domain objects and tables. The name of the file must follow certain specifications: domain object.hbm.xml, generally placed in the same folder as the domian object (that is, the same package Down)

The requirements for the domain object are as follows:

  • (1) The domain object should correspond to a table
  • (2) Generally, we put it under the com.xxx.domain package
  • (3) domain requires a primary key attribute (used to identify a domain object)
  • (4) In addition to the primary key attribute, it should have other attributes, and the access permission of the attribute is private
  • (5) Provide setter and getter methods
  • (6) There should be a no-argument constructor (hibernate reflection)

The domain object is as follows:

public class Employee {
    private Integer id;
    private String name;
    private String email;
    private Date hiredate;

    public Integer 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 String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getHiredate() {
        return hiredate;
    }

    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }
}

The configuration file is as follows:

<?xml version="1.0" encoding="utf-8" ?>
<!--XML文件需要DTD文件来规定格式-->
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/xsd/hibernate-mapping-3.0.dtd">

<!--package用于指定映射domain对象所在的包-->
<hibernate-mapping package="com.gavin.domain">
    <!--name用于指定映射的domain对象,table用于指定数据库中的表-->
    <class name="Employee" table="employee">
        <!--id元素用于指定domain对象中与表对应的主键属性,column用于指定表中的主键属性-->
        <!--当然一般我们的命名是一致的,这里都是id-->
        <id name="id" column="id" type="java.lang.Integer"/>
        <!--对其他属性还要配置-->
        <!--指定属性name,是String类型的,其对应表中的列为name,并且不允许为空-->
        <property name="name" type="java.lang.String">
            <column name="name" not-null="false"/>
        </property>
        <property name="email" type="java.lang.String">
            <column name="email" not-null="false"/>
        </property>
        <property name="hiredate" type="java.util.Date">
            <column name="hiredate" not-null="false"/>
        </property>
    </class>
</hibernate-mapping>

6. Manually configure our hibernate.cfg.xml file, which is used to configure the type of database connection, driver, user name, password, url, etc., and also manage the object relationship mapping file. We generally do not modify the name of this file.

The hibernate.cfg.xml configuration file is as follows:

<?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>
        <!--hibernate设计者给我们提供了一些常用设置的配置-->
        <!--show_sql可以让Hibernate输出SQL语句-->
        <property name="show_sql">true</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3333/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">your_password</property>
        <!--配置dialect方言,明确告诉Hibernate现在连接的是哪种数据库-->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 下面这个配置指定Hibernate自动帮我们创建表(如果数据库中没有该表的话)。-->
        <!--create表示每次使用都创建新表,如果存在表,则删除过再创建-->
        <!--update则表示如果表结构有变化,则删除后创建新表,如果没有,则不创建新表-->
        <!-- <property name="hbm2ddl.auto">create</property> -->
        <!--mapping用于指定对象关系映射文件-->
        <mapping resource="com/gavin/domain/Employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

7. Test file TestMain.java

package com.gavin.view;

import com.gavin.domain.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import java.util.Date;

public class TestMain {
    public static void main(String[] args) {
        addEmployee();
    }

    /**
     * 向数据库中添加一个Employee对象
     */
    public static void addEmployee() {
        // 我们使用Hibernate完成CRUD操作
        // 这里我们只见对象,不见表了;也就是说,我们不关心表了,对表的操作由Hibernate接管了
        // 我们不使用service,直接测试
        // 1.创建Configuration,并调用configure方法读取配置文件完成初始化,
        // 默认的文件名为hibernate.cfg.xml,故可以不写文件名
        Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
        // 2.创建SessionFactory,这是一个会话工厂,是一个重量级的类
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        // 3.创建一个会话,相当于JDBC中的Connection
        Session session = sessionFactory.openSession();

        /*对于Hibernate而言,要求程序在进行增加,删除,修改的时候使用事务提交*/

        Transaction transaction = session.beginTransaction();

        // 4.添加一个Employee
        Employee employee = new Employee();
        employee.setName("Gavin");
        employee.setEmail("[email protected]");
        employee.setHiredate(new Date());

        // 之前的插入是insert语句,现在不用了
        // 直接调用session.save(),就可以将Employee对象插入数据库
        session.save(employee); // save employee 就是持久化该对象(把数据保存到了数据库中)
        transaction.commit();
        session.close();
    }
}

Running the above test file, Hibernate will insert a piece of data into the database. show_sqlSince we set the property to be when we configure Hibernate true, the console will output the SQL statement executed by Hibernate.

write picture description here

The images below show the results of querying the database before and after running the test code.

write picture description here

Our directory structure is as follows:

write picture description here

more tests

1. SessionFactory is a heavyweight class, so it should be guaranteed to be monomorphic. So encapsulate it. as follows:

package com.gavin.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * 单例模式
 *
 * 在使用Hibernate开发项目的时候,一定保证只有一个SessionFactory,
 * 原则:理论上是一个数据库对应一个SessionFactory,项目中用了两个数据库,则可以存在两个SessionFactory
 */
final public class MySessionFactory {
    private static SessionFactory sessionFactory;

    static{
        sessionFactory = new Configuration().configure().buildSessionFactory();
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    private MySessionFactory(){}
}

2. At this point, we test the modification of Employee, write the updateEmployeemethod and call the execution.

public static void main(String[] args) {
    // addEmployee();
    updateEmployee();
}

/**
    * 修改Employee
    */
public static void updateEmployee() {
    // 获取一个会话
    Session session = MySessionFactory.getSessionFactory().openSession();

    // 获取要修改的对象,再修改
    Transaction transaction = session.beginTransaction();
    // load是通过主键属性获取对象实例 <--> 与表的记录对应
    Employee employee = session.load(Employee.class, 1);
    // 下面这句话会导致一个update语句产生
    employee.setEmail("[email protected]");
    transaction.commit();
    session.close();
}

After successful execution, the data in the database is as follows:

write picture description here

As you can see, the data in the database has been modified.

3. Similarly, we can test deletion.

public static void main(String[] args) {
    // addEmployee();
    // updateEmployee();
    delectEmployee();
}

public static void delectEmployee() {
    // 获取一个会话
    Session session = MySessionFactory.getSessionFactory().openSession();
    // 删除,先获取该雇员,然后再删除
    Transaction transaction = session.beginTransaction();
    Employee employee = session.load(Employee.class, 1);
    session.delete(employee);
    transaction.commit();
    session.close();
}

4. The function of query will be introduced later. We have already used a session.load()method to get an object, but the query is diverse, it does not necessarily have idto be queried by number, and there are more query requirements such as paging, etc., and the HQLstatement will be focused on later.

Use tools (IDEA) to automatically generate domain objects and hbm configuration files

As mentioned earlier, there are three ways to develop Hibernate. In the previous example, we used the second development method, namely: 由DB开始,用工具生成mapping和Domain Object (使用较多).

In the previous examples, we wrote code and configuration files manually, in fact, these steps can be completed by tools for us.

There is such an operation in MyEclipse, and IDEA also has it. The following describes the operation in IDEA.

1. First of all, the directory structure is as follows. We back up the original domain object and configuration file in the pojopackage first. At the same time delete hibernate.cfg.xmlthe configuration in the file mapping(this configuration will be added automatically by the tool later).

Below the Project box there is the Persistence tool box, this is where we operate the Hibernate tools.

write picture description here

2. First we need to configure the database

write picture description here

Set database connection parameters, IP, user name and password, etc. in the pop-up dialog box.

write picture description here

3. Right HibernateTestclick and select Generate Persistence MappingandBy Database Scheme

write picture description here

4. Make settings in the pop-up dialog box, as follows:

write picture description here

5. After the above operations are completed, we can see the generated Employeeobject and Employee.hbm.xmlrelationship mapping files under the domain package.

write picture description here

At this point we tested again TestMainand found nothing unusual.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325655401&siteId=291194637