开发步骤:java
建议使用 Maven 构建工程(如何构建 Maven 工程),在 POM 文件中添加相关依赖。mysql
<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>
hibernate.cfg.xml
如下操做前提是 Eclipse 中已经安装了 Hibernate 插件sql
2.1 右键工程 New
-> Other...
-> Hibernate
-> Hibernate Configuration File (cfg.xml)
数据库
2.2 点击 Next >
,选择配置文件的存储位置并命名,默认命名是 hibernate.cfg.xml
session
2.3 点击 Next >
,设置数据库方言(dialect)、驱动、连接URL、用户名、密码等 注意:Hibernate 经常使用属性(譬如数据库方言)能够查看如下路径文件:Hibernate 根目录 -> project
-> etc
-> hibernate.properties
app
2.4 点击 Finish,生成的配置文件以下:less
<?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.
能够省略。ide
<?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>
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.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>
<?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>
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(); } }
一月 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>
查询数据库结果: