Hibernate:入门简介

来源:互联网 发布:c语言中memcpy函数 编辑:程序博客网 时间:2024/06/05 14:52

本文内容大多基于官方文档和网上前辈经验总结,经过个人实践加以整理积累,仅供参考。


Hibernate 开发步骤:

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 插件

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

这里写图片描述

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

这里写图片描述

点击 Next >,设置数据库方言(dialect)、驱动、链接URL、用户名、密码等

注意:Hibernate 常用属性(譬如数据库方言)可以查看以下路径文件:Hibernate 根目录 -> project -> etc -> hibernate.properties

这里写图片描述

点击 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>

在该配置文件中添加一些注释及其他补充信息,注意每个 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 风格为持久化类的属性设置 getset 方法

(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

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

这里写图片描述

点击 Next> -> Add Class...

这里写图片描述

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

这里写图片描述

一路 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 logVersionINFO: 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 resolveEntityWARN: 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 configureWARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)一月 29, 2017 7:30:26 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreatorINFO: 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 buildCreatorINFO: HHH10001001: Connection properties: {user=root, password=****}一月 29, 2017 7:30:26 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreatorINFO: 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 getIsolatedConnectionINFO: 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 stopINFO: 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>,如果设置为 falseSQL 会在显示在一行内

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

查询数据库结果:

这里写图片描述

0 0
原创粉丝点击