How to use Hibernate

The first Hibernate program

Step 1: Create a new project and import the jar package

Add the jar package used to develop the hibernate project. The downloaded Hibernate rack package file, after decompression, there are eight rack packages in the /Hibernate/lib/required path. These are the minimum rack packages of Hibernate. There are more optional packages under lib, which can be imported as needed.
write picture description here
Import the database JAR package
write picture description here

Step 2: Add the Hibernate configuration file hibernate.cfg.xml

Configuration file path in hibernate download package:
Path: hibernate-release-5.0.2.Final\project\hibernate-ehcache\src\test\resources\hibernate-config

File: hibernate.cfg.xml
The Hibernate configuration file is used to configure the database connection and various properties (such as database driver name, database address, user name, password, database dialect, etc.) required by the database connection and Hibernate runtime. The java property document (properties) exists in the classpath of the application (usually saved to the src root directory of the project), and the default file name uses hibernate.cfg.xml. Hibernate will automatically look for this file in the classpath and read the configuration information when it is initialized.
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-configuration>
  <session-factory>
<!--  定义数据库连接驱动-->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!--定义数据库服务器地址-->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<!--数据库用户名-->
<property name="hibernate.connection.username">root</property>
<!--数据库用户对应的密码-->
<property name="hibernate.connection.password">root</property>
<!--数据库对应的方言-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!--在操作数据库时是否打印SQL语句-->
<property name="hibernate.show_sql">true</property>
<!-- 指定是否对输出的 SQL 语句进行格式化 -->
<property name="hibernate.format_sql">true</property>
<!--打开hbm2ddl.auto选项,就是如果我们的mysql里面没有该test数据库则自动创建test数据库里面的表-->
<property name="hbm2ddl.auto">update</property>
<!--配置ORM映射文件-->
<mapping resource="cn/rjtraining/model/User.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

hibernate.hbm2ddl.auto:取值create、create-drop、update、validate、none

Create: Every time hibernate is loaded, the last generated table will be deleted, and then a new table will be regenerated according to your model class, even if there is no change twice, this is an important reason for the loss of database table data .

create-drop: A table is generated according to the model class every time hibernate is loaded, but the table is automatically deleted as soon as the sessionFactory is closed.

update: When hibernate is loaded for the first time, the table structure is automatically established according to the model class (provided that the database is established first), and the table structure is automatically updated according to the model class when hibernate is loaded later. Even if the table structure changes, the rows in the table still exist. Delete the previous line. It should be noted that when deployed to the server, the table structure will not be established immediately, it will not be established until the application is run for the first time.

validate: It will be compared with the table in the database. If the column in the .hbm.xml file does not exist in the data table, an exception will be thrown. (It will only be compared with the table in the database, no new table will be created, but will insert the new value)

When developing and debugging initialized data, you can choose create and update
. When the website is officially released, it is very dangerous to automatically update the existing data or table structure of the database. At this time, the DBA (DateBase Administrator) comrade should manually perform the background. database operations. The suggested value for hibernate.hbm2ddl.auto is "none" or "validate".

Step 3: Create a persistent class

The persistent class should correspond to the database table, and the behavior of manipulating the database in the application is essentially converted into the operation of the persistent class. Take the User table as an example, create a persistent class User for the table.

package cn.rjtraining.model;
import java.io.Serializable;
public class User implements Serializable{
private Integer uid;
private String uname;
private String password;
private String role;
//省略Getters和Setters方法
}

When creating persistent classes, keep the following in mind

  1. The created persistent class is recommended to implement the Serializable serialization interface (hibernate has a second-level cache, the cache will write the object to the hard disk, and it must be serialized)
  2. Create an identity property id for the persistent class that maps the primary key field of the data table
  3. Each property of the class is of private type, and provides public type accessors (setter and getter methods) for each property of the class

Step 4: Define the ORM mapping file

Hibernate uses XML format files to specify the mapping between objects and relational data. At runtime, Hibernate will generate various SQL statements based on this mapping file,
such as the mapping file User.hbm.xml between the User class and the data table User

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<!-- 配置类名,也就是User类对应数据库中的user表,user表是test数据库中的 -->
    <class name="cn.rjtraining.model.User" table="user" catalog="test">
    <!-- 第一,配置主键,主键的数据类型为Integer -->
        <id name="uid" type="java.lang.Integer">
    <!-- 对应数据库中的列名为uid,可以不写,那么默认的就是uid -->
            <column name="uid" />
            <!-- 主键的生成策略,采用数据库中提供的生成策略 -->
            <generator class="native" />
        </id>
        <property name="uname" type="java.lang.String">
            <column name="uname" length="25" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="password" length="25" />
        </property>
        <property name="role" type="java.lang.String">
            <column name="role" length="25" />
        </property>
    </class>
</hibernate-mapping>

In the mapping file, the element is used as the root element of the document, and the root element contains child elements. The elements are used to configure the mapping relationship between persistent classes and data tables in the program. The syntax format is as follows:

Step 5: Write a test class to test the hibernate environment we set up in the previous steps.

Import import org.junit.*; packages for testing.

package cn.rjtraining.model;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class Testhibernate {
@Test
public void test(){
SessionFactory sessionFactory = null;
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
//3.开启事务
Transaction transaction = session.beginTransaction();
//4.执行保存操作
User user = new User("admin","11111","2");//无主键
session.save(user);
//5.提交事务 
transaction.commit();
//6.关闭session
session.close();
//7.关闭 SessionFactory 对象
sessionFactory.close();
}
}

Step 6: Run the Test Class

After successful operation, a user table will be created in the test database, and a piece of data will be stored in the table, indicating that the Hibernate environment has been successfully built.


The main process of Hibernate

The first step: read and parse the configuration file hibernate.cfg.xml, which is mainly implemented by the configure() method of the Configuration class.
Step 2: Read and parse the mapping file *.hbm.xml, and implement it through the buildSessionFactory(serviceRegistry) method of the Configuration class, which will return a session factory SessionFactory.
Step 3: Open the session Session, which is implemented by the openSession() method of the SessionFactory.
Step 4: Create the transaction management object Transaction, which is created by the beginTransaction() method of the Session object.
Step 5: Operate on the database. The operation of the database mainly relies on some methods of the Session class to implement, such as the load() method, delete() method, save() method, etc., to realize the CRUD operation on the database.
Step 6: Submit the transaction. After completing the operation on the database, the transaction should be submitted to complete the persistence of the data in the database.
Step 7: Close the Session and SessionFactory objects to free up memory space.

Guess you like

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