開發步驟: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>
查詢數據庫結果: