在學習 Hibernate 以前,咱們先來了解ORM 對象關係映射java
O, Object 對象mysql
R,Realtion 關係 (關係型數據庫: MySQL, Oracle…)sql
M,Mapping 映射數據庫
ORM, 解決什麼問題?數組
存儲: 可否把對象的數據直接保存到數據庫? session
獲取: 可否直接從數據庫拿到一個對象?app
想作到上面2點,必需要有映射!ide
總結:學習
Hibernate與ORM的關係?測試
Hibernate是ORM的實現,簡化對數據的操做。
好 ,接下來熟悉的helloworld
首先,咱們須要搭建Hibernate 環境
在這裏我演示使用的版本:hibernate-distribution-3.6.0.Final
咱們 新建一個javaproject 項目 新建bin目錄 導入jar
hibernate3.jar核心 + required 必須引入的(6個) + jpa 目錄 + 數據庫驅動包
Employee.java 對象
package com.yif.a_hello; import java.util.Date; public class Employee { private int empId; private String empName; private Date workDate; @Override public String toString() { return "Employee [empId=" + empId + ", empName=" + empName + ", workDate=" + workDate + "]"; } public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public Date getWorkDate() { return workDate; } public void setWorkDate(Date workDate) { this.workDate = workDate; } }
Employee.hbm.xml 對象的映射 (映射文件)
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.yif.a_hello"> <class name="Employee" table="employee"> <!-- 主鍵 ,映射--> <id name="empId" column="id"> <generator class="native"/> </id> <!-- 非主鍵,映射 --> <property name="empName" column="empName"></property> <property name="workDate" column="workDate"></property> </class> </hibernate-mapping>
-à 數據庫鏈接配置
-à 加載所用的映射(*.hbm.xml)
<!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節點表明一個數據庫 --> <session-factory> <!-- 1. 數據庫鏈接配置 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql:///hib_demo?useUnicode=true&characterEncoding=UTF8</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">密碼</property> <!-- 數據庫方法配置,hibernate在運行的時候,會根據不一樣的方言生成符合當前數據庫語法的sql --> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- 2. 其餘相關配置 --> <!-- 2.1 顯示hibernate在運行時候執行的sql語句 --> <property name="hibernate.show_sql">true</property> <!-- 2.2 格式化sql --> <property name="hibernate.format_sql">true</property> <!-- 2.3 自動建表 --> <property name="hibernate.hbm2ddl.auto">create</property> <!-- 3. 加載全部映射 --> <mapping resource="com/yif/a_hello/Employee.hbm.xml"/> </session-factory> </hibernate-configuration>
package com.yif.a_hello; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Test; public class App { @Test public void testHello() throws Exception { // 對象 Employee emp = new Employee(); emp.setEmpName("Hello"); emp.setWorkDate(new Date()); // 獲取加載配置文件的管理類對象 Configuration config = new Configuration(); config.configure(); // 默認加載src/hibenrate.cfg.xml文件 // 建立session的工廠對象 SessionFactory sf = config.buildSessionFactory(); // 建立session (表明一個會話,與數據庫鏈接的會話) Session session = sf.openSession(); // 開啓事務 Transaction tx = session.beginTransaction(); //保存-數據庫 session.save(emp); // 提交事務 tx.commit(); // 關閉 session.close(); sf.close(); } }
目錄結構:
結果:
該案例會自動建立表 ,由於主配置文件hibernate.cfg.xml 中
<!-- 2.3 自動建表 --> <property name="hibernate.hbm2ddl.auto">create</property> 後面會專門對主配置文件進行講解。
|-- Configuration 配置管理類對象
config.configure(); 加載主配置文件的方法(hibernate.cfg.xml) 默認加載src/hibernate.cfg.xml
config.configure(「cn/config/hibernate.cfg.xml」); 加載指定路徑下指定名稱的主配置文件
config.buildSessionFactory(); 建立session的工廠對象
sf = new Configuration().configure().buildSessionFactory();
|-- SessionFactory session的工廠(或者說表明了這個hibernate.cfg.xml配置文件)
sf.openSession(); 建立一個sesison對象
sf.getCurrentSession(); 建立session或取出session對象
private static SessionFactory sf; static { /* //1. 建立配置管理類對象 Configuration config = new Configuration(); // 加載配置文件 (默認加載src/hibernate.cfg.xml) config.configure(); //2. 根據加載的配置管理類對象,建立SessionFactory對象 sf = config.buildSessionFactory(); */ // 建立sf對象 sf = new Configuration().configure().buildSessionFactory(); }
session對象維護了一個鏈接(Connection), 表明了與數據庫鏈接的會話。
Hibernate最重要的對象: 只用使用hibernate與數據庫操做,都用到這個對象
session.beginTransaction(); 開啓一個事務; hibernate要求全部的與數據庫的操做必須有事務的環境,不然報錯!
session.save(obj); 保存一個對象
//1. 保存對象 @Test public void testSave() throws Exception { // 對象 Employee emp = new Employee(); emp.setEmpName("張三123"); emp.setWorkDate(new Date()); //根據session的工廠,建立session對象 Session session = sf.openSession(); // 開啓事務 Transaction tx = session.beginTransaction(); //-----執行操做----- session.save(emp); // 提交事務/ 關閉 tx.commit(); session.close(); }
session.update(emp); 更新一個對象
//更新 @Test public void testUpdate() throws Exception { // 對象 Employee emp = new Employee(); emp.setEmpId(1); emp.setEmpName("修改"); // 建立session Session session = sf.openSession(); Transaction tx = session.beginTransaction(); //-------執行操做------- // 沒有設置主鍵,執行保存;有設置主鍵,執行更新操做; 若是設置主鍵不存在報錯! session.saveOrUpdate(emp); tx.commit(); session.close(); }
session.saveOrUpdate(emp); 保存或者更新的方法:
主鍵查詢:
session.get(Employee.class, 1); 主鍵查詢
session.load(Employee.class, 1); 主鍵查詢 (支持懶加載)
HQL查詢與SQL查詢區別:
SQL: (結構化查詢語句)查詢的是表以及字段; 不區分大小寫。
HQL: hibernate query language 即hibernate提供的面向對象的查詢語言
查詢的是對象以及對象的屬性。
區分大小寫。
//HQL查詢 【適合有數據庫基礎的】 @Test public void testQuery() throws Exception { Session session = sf.openSession(); Transaction tx = session.beginTransaction(); // 主鍵查詢 //Employee emp = (Employee) session.get(Employee.class, 1); // HQL查詢,查詢所有 Query q = session.createQuery("from Employee where empId=1 or empId=2"); List<Employee> list = q.list(); System.out.println(list); tx.commit(); session.close(); }
徹底面向對象的查詢。
//QBC查詢 , query by criteria 徹底面向對象的查詢 @Test public void testQBC() throws Exception { Session session = sf.openSession(); Transaction tx = session.beginTransaction(); Criteria criteria = session.createCriteria(Employee.class); // 條件 criteria.add(Restrictions.eq("empId", 1)); // 查詢所有 List<Employee> list = criteria.list(); System.out.println(list); tx.commit(); session.close(); }
複雜的查詢,就要使用原生態的sql查詢,也能夠,就是本地sql查詢的支持!
(缺點: 不能跨數據庫平臺!)
//sQL @Test public void testSQL() throws Exception { Session session = sf.openSession(); Transaction tx = session.beginTransaction(); // 把每一行記錄封裝爲對象數組,再添加到list集合 // SQLQuery sqlQuery = session.createSQLQuery("select * from employee"); // 把每一行記錄封裝爲 指定的對象類型 SQLQuery sqlQuery = session.createSQLQuery("select * from employee").addEntity(Employee.class); List list = sqlQuery.list(); System.out.println(list); tx.commit(); session.close(); }
|-- Transaction hibernate事務對象
問題1:
ClassNotFoundException…., 缺乏jar文件!
問題2:
若是程序執行程序,hibernate也有生成sql語句,但數據沒有結果影響。
問題通常是事務忘記提交…….
遇到問題,必定看錯誤提示!