您的位置:首页 > 其它

2 Hibernate:入门简介

2017-07-02 00:00 309 查看
开发步骤:

1 导入 Hibernate 库文件及开发所用数据库的驱动文件

建议使用 Maven 构建工程(如何构建 Maven 工程),在 POM 文件中添加相关依赖。

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.5.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
</dependencies>

2 创建 Hibernate 配置文件:
hibernate.cfg.xml

以下操作前提是 Eclipse 中已经安装了 Hibernate 插件

2.1 右键工程
New
->
Other...
->
Hibernate
->
Hibernate Configuration File (cfg.xml)




2.2 点击
Next >
,选择配置文件的存储位置并命名,默认命名是
hibernate.cfg.xml




2.3 点击
Next >
,设置数据库方言(dialect)、驱动、链接URL、用户名、密码等
注意:Hibernate 常用属性(譬如数据库方言)可以查看以下路径文件:Hibernate 根目录 ->
project
->
etc
->
hibernate.properties




2.4 点击 Finish,生成的配置文件如下:

<?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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
</session-factory>
</hibernate-configuration>

2.5 在该配置文件中添加一些注释及其他补充信息,注意每个
property
元素名称的前缀
hibernate.
可以省略。

<?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>
<!-- 配置数据库基本信息 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>

<!-- 配置Hibernate基本信息 -->
<!-- Hibernate使用的数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 执行操作时是否在控制台打印SQL -->
<property name="show_sql">true</property>
<!-- 是否对打印的SQL进行格式化 -->
<property name="format_sql">true</property>
<!-- 指定自动生成数据表的策略 -->
<property name="hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>

3 创建持久化类

Hibernate 对持久化类的要求:

(1) 提供无参构造器,Hibernate 通过反射(Constructor.newInstance())实例化持久化类的对象

(2) 提供一个标识属性,映射数据库表的主键

(3) 使用 JavaBean 风格为持久化类的属性设置 get 和 set 方法

(4) 持久化类是非 final 类,Hibernate 无法为 final 类生成 CGLIB 代理

package lesson.hibernate;

import java.sql.Date;

public class Person {

private int id;

private String account;

private String name;

private Date birth;

public Person() {}

public Person(String account, String name, Date birth) {
super();
this.account = account;
this.name = name;
this.birth = birth;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getAccount() {
return account;
}

public void setAccount(String account) {
this.account = account;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Date getBirth() {
return birth;
}

public void setBirth(Date birth) {
this.birth = birth;
}

@Override
public String toString() {
return "Person [id=" + id + ", account=" + account + ", name=" + name + ", birth=" + birth + "]";
}

}

4 创建对象-关系映射文件:*.hbm.xml

4.1 右键工程
New
->
Other...
->
Hibernate
->
Hibernate XML Mapping file (hbm.xml)




4.2 点击
Next>
->
Add Class...




4.3 选择需要映射的类,点击
OK




4.4 一路
Next>
,最后点击
Finish








生成的映射文件:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2017-1-29 13:30:42 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="lesson.hibernate.Person" table="PERSON">
<id name="id" type="int">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="account" type="java.lang.String">
<column name="ACCOUNT" />
</property>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="birth" type="java.sql.Date">
<column name="BIRTH" />
</property>
</class>
</hibernate-mapping>

持久化类的 id 属性对应数据库主键,修改主键生成方式。

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2017-1-29 13:30:42 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="lesson.hibernate.Person" table="PERSON">
<id name="id" type="int">
<column name="ID" />
<!-- 指定主键生成方式:native是数据库本地方式 -->
<generator class="native" />
</id>
<property name="account" type="java.lang.String">
<column name="ACCOUNT" />
</property>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="birth" type="java.sql.Date">
<column name="BIRTH" />
</property>
</class>
</hibernate-mapping>

5 将对象-关系映射文件加入 Hibernate 配置文件

<?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>
<!-- 配置数据库基本信息 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>

<!-- 配置Hibernate基本信息 -->
<!-- Hibernate使用的数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 执行操作时是否在控制台打印SQL -->
<property name="show_sql">true</property>
<!-- 是否对打印的SQL进行格式化 -->
<property name="format_sql">true</property>
<!-- 指定自动生成数据表的策略 -->
<property name="hbm2ddl.auto">update</property>

<!-- 指定关联的.hbm.xml映射文件 -->
<mapping resource="lesson/hibernate/Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>

6 通过 Hibernate API 编写访问数据库的代码

package lesson.hibernate;

import java.sql.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class HibernateTest {

@Test
public void test() {
// 1 创建一个Configuration对象,加载Hibernate的基本配置信息和对象关系映射信息
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
// 2 通过Configuration对象的buildSessionFactory()方法创建一个SessionFactory对象
SessionFactory sessionFactory = configuration.buildSessionFactory();
// 3 创建一个Session对象
Session session = sessionFactory.openSession();
// 4 开启事务
Transaction transaction = session.beginTransaction();
// 5 执行操作
Person person = new Person("admin", "Mike", new Date(System.currentTimeMillis()));
session.save(person);
// 6 提交事务
transaction.commit();
// 7 关闭Session
session.close();
// 8 关闭SessionFactory
sessionFactory.close();
}
}

7 运行单元测试,可以看到 log

一月 29, 2017 7:30:24 下午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.5.Final}
一月 29, 2017 7:30:24 下午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
一月 29, 2017 7:30:24 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
一月 29, 2017 7:30:24 下午 org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead.  Support for obsolete DTD/XSD namespaces may be removed at any time.
一月 29, 2017 7:30:26 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
一月 29, 2017 7:30:26 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://127.0.0.1:3306/hibernate]
一月 29, 2017 7:30:26 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
一月 29, 2017 7:30:26 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
一月 29, 2017 7:30:26 下午 org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Sun Jan 29 19:30:26 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
一月 29, 2017 7:30:26 下午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
一月 29, 2017 7:30:27 下午 org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@49f5c307] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate:

create table PERSON (
ID integer not null auto_increment,
ACCOUNT varchar(255),
NAME varchar(255),
BIRTH date,
primary key (ID)
)
Hibernate:
insert
into
PERSON
(ACCOUNT, NAME, BIRTH)
values
(?, ?, ?)
一月 29, 2017 7:30:28 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://127.0.0.1:3306/hibernate]

从日志中可以看到:

(1) 代码执行的 SQL,因为 Hibernate 配置文件中设置了 <property name="show_sql">true</property>,如果设置为 false 则日志中不会打印执行的SQL

(2) 日志打印的 SQL 是多行格式化显示的,因为 Hibernate 配置文件中设置了 <property name="format_sql">true</property>,如果设置为 false 则 SQL 会在显示在一行内

(3) 代码一共执行了两条 SQL,第 1 条 SQL 创建了 PERSON 表,第 2 条 SQL 向创建好的 PERSON 表中插入一条数据,因为 Hibernate 配置文件中设置了 <property name="hbm2ddl.auto">update</property>

查询数据库结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: