1、環境準備
【1】hibernate必須的jar包
① 在hibernate官網中下載:http://hibernate.org/
② 導入Hibernate下的jar包(lib->required下的所有jar包)
【2】加入數據庫驅動的jar包
2、hibernate的開發步驟
【1】創建hibernate的核心配置文件
主要是配置數據庫信息、配置hibernate信息以及實體類配置文件的配置。
該文件的命名是固定的:hibernate.cfg.xml
,文件的路徑是固定放在src下。
<?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.url">jdbc:mysql:///hibernate_db</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- 配置hibernate信息 -->
<!--執行操作時是否在控制檯打印sql-->
<property name="hibernate.show_sql">true</property>
<!--是否對sql進行格式化-->
<property name="hibernare.format_sql">true</property>
<!--指定自動生成數據表的策略-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 設置hibernate所使用的數據庫方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 指定關聯的hibernate映射文件 -->
<mapping resource="com/zm/hibernate/news.hbm.xml"/>
</session-factory>
</hibernate-configuration>
【2】創建持久化類
- 提供一個無參的構造器,以便使用反射來實例化持久化類。
- 提供一個標識屬性,通常映射爲數據庫表的主鍵字段,如果沒有該屬性,一些功能將不起作用。如:
Session.saveOrUpdate()
。 - 爲類的持久化字段聲明訪問方法(
get/set
)。 - 使用非
final
類,以便可以生成CGLIBE
動態代理。 - 重寫
equals
和hashCode
方法:如果需要把持久化類的實例放到Set中,則應該重寫這兩個方法。
public class News {
private int id;
private String title;
private String auth;
public News() {
}
public News(String title, String auth) {
this.id = id;
this.title = title;
this.auth = auth;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuth() {
return auth;
}
public void setAuth(String auth) {
this.auth = auth;
}
@Override
public String toString() {
return "News{" +
"id=" + id +
", title='" + title + '\'' +
", auth='" + auth + '\'' +
'}';
}
}
【3】創建對象-關係映射文件
該配置文件命名規範是實體類名+hbm.xml。
該文件存放的位置是任意的。通常將該關係映射文件放到與實體類對象同一目錄下。
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.zm.hibernate.News" table="news" schema="hibernate_db">
<id name="id" type="java.lang.Integer">
<column name="id" sql-type="int(11)"/>
<!-- 該id作爲主鍵並且自增加1 -->
<generator class="native"></generator>
</id>
<property name="title" type="java.lang.String">
<column name="title" sql-type="varchar(255)"/>
</property>
<property name="auth" type="java.lang.String">
<column name="auth" sql-type="varchar(255)"/>
</property>
</class>
</hibernate-mapping>
【4】通過hibernate api編寫訪問數據庫的代碼(測試)
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.創建一個SessionFactory對象
SessionFactory sessionFactory = null;
//1.1創建Configuration對象:對應Hibernate的基本配置信息和對象關係映射信息
Configuration configuration = new Configuration().configure();
//hibernate 3中sessionFactory的創建
// sessionFactory = configuration.buildSessionFactory();
//hibernate 4中sessionFactory的創建
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
//2.創建一個Session對象
Session session = sessionFactory.openSession();
//3.開啓事務
Transaction transaction = session.beginTransaction();
//4.執行保存操作
News news = new News("Java","Tom");
session.save(news);
//5.提交事務
transaction.commit();
//6.關閉Session
session.close();
//7.關閉SessionFactory對象
sessionFactory.close();
}
}
詳細說明
【1】Cpnfiguration類
- Configuration 類負責管理 Hibernate 的配置信息。包括如下內容:
– Hibernate 運行的底層信息:數據庫的URL、用戶名、密碼、JDBC驅動類,數據庫Dialect,數據庫連接池等(對應hibernate.cfg.xml
文件)。
– 持久化類與數據表的映射關係(*.hbm.xml
文件)。
– 創建Configuration的兩種方式
① Xml文件(hibernate.cfg.xml)
Configuration cfg = new Configuration().configure();
//Configuration 的 configure 方法還支持帶參數的訪問:
File file = new File(“simpleit.xml”);
Configuration cfg = new Configuration().configure(file);
② 屬性文件(hibernate.properties)
Configuration cfg = new Configuration();
【2】SessionFactory接口
- 針對單個數據庫映射關係經過編譯後的內存鏡像,是線程安全的。
- SessionFactory是生成Session的工廠。
【3】Session接口
- Session 是應用程序與數據庫之間交互操作的一個單線程對象,是 Hibernate 運作的中心,所有持久化對象必須在 session 的管理下才可以進行持久化操作。相當於JDBC的Connection。
【4】Transaction事務
- 代表一次原子操作,它具有數據庫事務的概念。所有持久層都應該在事務管理下進行,即使是隻讀操作。
Transaction tx = session.beginTransaction();
- 常用方法:
commit():提交相關聯的session實例
rollback():撤銷事務操作
wasCommitted():檢查事務是否提交
【5】Hibernate的兩個重要配置項
- hbm2ddl.auto
該屬性可幫助程序員實現正向工程, 即由 java 代碼生成數據庫腳本, 進而生成具體的表結構. 。取值create | update | create-drop | validate
create : 會根據 .hbm.xml 文件來生成數據表, 但是每次運行都會刪除上一次的表 ,重新生成表, 哪怕二次沒有任何改變
create-drop : 會根據 .hbm.xml 文件生成表,但是SessionFactory一關閉, 表就自動刪除
update : 最常用的屬性值,也會根據 .hbm.xml 文件生成表, 但若 .hbm.xml 文件和數據庫中對應的數據表的表結構不同, Hiberante 將更新數據表結構,但不會刪除已有的行和列
validate : 會和數據庫中的表進行比較, 若 .hbm.xml 文件中的列在數據表中不存在,則拋出異常
- format_sql
是否將 SQL 轉化爲格式良好的 SQL . 取值true | false
。