开发步骤:
1 导入 Hibernate 库文件及开发所用数据库的驱动文件
建议使用 Maven 构建工程(如何构建 Maven 工程),在 POM 文件中添加相关依赖。
junit junit 4.12 org.hibernate hibernate-core 5.2.5.Final mysql mysql-connector-java 5.1.40
2 创建 Hibernate 配置文件:hibernate.cfg.xml
以下操作前提是
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,生成的配置文件如下:
com.mysql.jdbc.Driver 123456 jdbc:mysql://localhost:3306/hibernate root org.hibernate.dialect.MySQL5InnoDBDialect
2.5 在该配置文件中添加一些注释及其他补充信息,注意每个 property
元素名称的前缀 hibernate.
可以省略。
com.mysql.jdbc.Driver jdbc:mysql://127.0.0.1:3306/hibernate root 123456 org.hibernate.dialect.MySQLDialect true true update
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
生成的映射文件:
持久化类的 id 属性对应数据库主键,修改主键生成方式。
5 将对象-关系映射文件加入 Hibernate 配置文件
com.mysql.jdbc.Driver jdbc:mysql://127.0.0.1:3306/hibernate root 123456 org.hibernate.dialect.MySQLDialect true true update
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.EnvironmentINFO: HHH000206: hibernate.properties not found一月 29, 2017 7:30:24 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager 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 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 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>,如果设置为 false 则 SQL 会在显示在一行内
(3) 代码一共执行了两条 SQL,第 1 条 SQL 创建了 PERSON 表,第 2 条 SQL 向创建好的 PERSON 表中插入一条数据,因为 Hibernate 配置文件中设置了 <property name="hbm2ddl.auto">update</property>
查询数据库结果: