Hibernate基礎知識(1)

一、什麼是Hibernate?

      Hibernate是輕量級JavaEE應用的持久層解決方案,是一個關係數據庫ORM框架。

      什麼是關係型數據庫?

      數據採用表方式存儲,表與表之間外鍵關聯。(MySQL、Oracle、SQLServer、DB2)

      什麼是ORM?

      Object Relational Mapping:對象關係映射

      ORM就是通過將Java對象映射到數據庫表,通過操作Java對象,就可以完成對數據表的操作。

      Hibernate是完全ORM的,只需要對對象進行操作,就可以生成底層SQL語句。


      流行的數據庫框架:

      1、JPA:Java Persistence API ,通過註解描述對象與數據表映射關係(只有接口規範)。

      2、Hibernate:最流行的ORM框架,通過對象-關係映射配置,可以完全脫離底層SQL,Hibernate實現JPA規範。

      3、Mybatis:本是Apache的一個開源項目iBatis,支持普通SQL查詢,存儲過程和高級映射的優秀持久層框架。*Mybatis並不是完全ORM,需要在xml中配置SQL語句。

      4、Apache DBUtils、Spring JDBCTemplate

      SQL語句封裝程度:Hibernate>MyBatis>Apache DBUtils 、Spring JDBCTemplate


二、爲什麼要使用Hibernate?

      Hibernate對JDBC訪問數據庫的代碼做了封裝,大大簡化了數據庫訪問層繁瑣的重複性代碼。

      Hibernate是一個基於JDBC的主流持久化框架,是一個優秀的ORM實現,它很大程度的簡化了dao層編碼工作。

      Hibernate使用java的反射機制,而不是字節碼增強程序類實現透明性。

      Hibernate的性能非常好,因爲它是一個輕量級框架。映射的靈活性很出色。它支持很多關係型數據庫,從一對一到多對多的各種複雜關係。

      *Hibernate本身性能並不是很好,存在很多優化手段(一級緩存、二級緩存、查詢緩存、抓取策略)


三、使用Hibernate框架快速入門

      1、去 http://sourceforge.net/projects/hibernate/files/hibernate3/ 下載 hibernate3 開發包

      hibernate 是 JBOSS 框架, JBOSS 是 EJB服務器, JBOSS 推出JBPM 工作流

      ***** hibernate 還有很多擴展技術 search 、 validator  ....


      2、目錄結構

      documentation:文檔

      lib:開發jar包

      project:Hibernate源碼

      hibernate3.jar:hibernate框架開發核心jar包


      3、導入jar包

      hibernate3.jar (核心jar包)

      lib/required/*.jar (6個)

      lib/jpa/hibernate-jpa-2.0-api-1.0.1.Final.jar (用語JPA註解開發,web開發)

      數據庫驅動jar包


      -----------------------------------------------------------------------------------------------------------

      日誌相關:

      hibernate 3.x版本 默認採用日誌技術 slf4j (即簡單日誌門面(SimpleLoggingFacadeforJava)) ,不是具體的日誌解決方案,它只服務於各種各樣的日誌系統。

      *  使用slf4j 好處,很容易整合其他日誌技術

      企業java開發,最主流日誌技術log4j。

      slf4j-api-1.6.1.jar沒有日誌實現,只是藉口,整合log4j。

      導入 slf4j-log4j12-1.7.2.jar  (slf4j對log4j 框架整合 )
      導入 log4j-1.2.16.jar  (log4j的日誌jar包 )

      -------------------------------------------------------------------------

      log4j是企業主流日誌技術,是Apache公司提供

      1)什麼是日誌技術,開發中爲什麼使用日誌技術?

      日誌:在系統運行過程中,記錄關鍵信息,記錄錯誤異常信息的技術。

      *區分System.out和日誌技術:

      System.out向控制檯輸入信息,一定輸出

      日誌技術:存在級別,通過級別控制日誌是否輸出,輸出的詳細程度,輸出的目的地(控制檯、文件、發送郵件)

      使用日誌:主要用於開發過程中調試和項目上線後的維護(記錄bug)


      2)使用log4j通過配置文件,配置日誌框架使用

      src/log4j.xml

      src/log4j.properties

  

      配置log4j.properties有三個組件

      組件一:記錄器(Loggers)用來配置日誌輸出級別,使用哪些輸出源。格式:記錄器名 = 級別,輸出源1,輸出源2……

            *一個記錄器指定多個輸出源

            log4j.rootLogger=info,stdout   info是日誌級別,stdout是輸出源名稱。

            *log4j提供日誌級別,由高到低:fatal(致命錯誤),error(普通錯誤),warn(警告),info(信息),debug(調試),trace(堆棧)

            *log4j記錄日誌時,只會記錄配置級別更高的信息

       組件二:輸出源(Appenders)在log4j中可以定義多個輸出源(控制檯、日誌文件、郵件、數據庫)

            *log4j.appender.輸出源名稱 = 實現類

            log4j.appender.stdout=org.apache.log4j.ConsoleAppender 向控制檯輸出

            log4j.appender.file=org.apache.log4j.FileAppender向文件輸出

      組件三:佈局(Layouts)在日誌中都記錄哪些信息

            log4j.appender.stdout.layout=org.apache.log4j.PatternLayout自定義佈局

            log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n  自定義佈局格式


      3)在程序中使用log4j記錄日誌

      步驟一:定義記錄器

      private static final Logger LOG = Logger.getLogger(Log4jTest.class);

      步驟二:使用log4j提供每個級別方法記錄日誌

      LOG.fatal("致命錯誤");
      LOG.error("普通錯誤");
      LOG.warn("警告信息");
      LOG.info("普通信息");
      LOG.debug("調試信息");
      LOG.trace("堆棧信息");
      * 常用 : error、warn、info、debug

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

4、編寫數據表和實體類

create table customer(
    id int primary key auto_increment,
	name varchar(20),
	age int ,
	city varchar(20)
);
package lsq.hibernate.domain;

public class Customer {
	private int id;
	private String name;
	private int age;
	private String city;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	@Override
	public String toString() {
		return "Customer [id=" + id + ", name=" + name + ", age=" + age
				+ ", city=" + city + "]";
	}
}
      完成實體類和數據表的映射配置

      hibernate 完全ORM,只需要操作Customer類對象, 自動生成SQL 操作customer 表

      1) 在類所有包,創建 類名.hbm.xml 文件   (Customer.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>
	<!-- 1、類與表的映射 -->
	<!-- 
		name:類名
		table:表名
		catalog:數據庫名
	 -->
	<class name="lsq.hibernate.domain.Customer" table="customer" catalog="hibernate3day1">
		<!-- 2、類中屬性與表中數據列映射 -->
		<!-- 主鍵 -->
		<!-- 
			name 屬性名(類中)
			column 列名 (表中)
			type 類型
		 -->
		<id name="id" column="id" type="int">
			<!-- 主鍵策略identity主鍵自增長 -->
			<generator class="native"></generator>
		</id>
		<!-- 普通屬性 -->
		<property name="name" column="name" type="java.lang.String" not-null="true"></property><!-- java類型 -->
		<property name="age" column="age" type="int"></property>
		<property name="city">
			<column name="city" sql-type="varchar(20)"></column><!-- SQL類型 -->
		</property>
	</class>
	
</hibernate-mapping>

      2)hibernate3.jar org/hibernate/hibernate-mapping-3.0.dtd

      配置屬性到列映射時,指定類型,類型有三種寫法
      第一種 java類型  java.lang.String
      第二種 hibernate類型 string
      第三種 SQL類型 varchar(20)
      
5、配置hibernate核心配置文件 
      在src下創建 hibernate.cfg.xml
      規則參見 hibernate3.jar /org/hibernate/hibernate-configuration-3.0.dtd

      配置hibernate基本屬性,參考 解壓目錄/project/etc/hibernate.properties 
      1) JDBC連接屬性
      2)數據庫方言
      3)其它屬性
      4)加載hbm映射文件

<?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>
	<!-- 配置會話工廠(hibernate核心對象,管理數據庫連接池) -->
	<session-factory>
		<!-- 連接數據庫JDBC四個基本連接參數 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql:///hibernate3day1</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<!-- 配置hibernate使用的數據庫方言(方言解決不同數據庫之間的區別) -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 其它屬性 -->
		<!-- 自動建表 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		<!-- 在日誌中輸出SQL -->
		<property name="hibernate.show_sql">true</property>
		<!-- 格式化SQL -->
		<property name="hibernate.format_sql">true</property>
		
		<!-- 加載hbm映射 -->
		<mapping resource="lsq/hibernate/domain/Customer.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

6、 編程操作hibernate框架(模板)

// 實例化配置對象,加載配置文件 hibernate.cfg.xml
Configuration configuration = new Configuration().configure();
// 創建會話連接工廠
SessionFactory sessionFactory = configuration.buildSessionFactory();
// 創建會話	
Session session = sessionFactory.openSession();
// 開啓事務
Transaction transaction = session.beginTransaction();
...  這裏可以編寫hibernate操作代碼邏輯 (********************************************************)
// 提交事務,釋放資源		
transaction.commit();
session.close();
sessionFactory.close();
7、 完成customer表增刪改查操作

      1) 使用 session對象 save方法 完成 insert 操作
            session.save(customer);

測試代碼:

	@Test
	//插入
	public void testInsert(){
		// 實例化配置對象,加載配置文件 hibernate.cfg.xml
		Configuration configuration = new Configuration().configure();
		// 創建會話連接工廠
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		// 創建會話	
		Session session = sessionFactory.openSession();
		// 開啓事務
		Transaction transaction = session.beginTransaction();
		
		Customer customer = new Customer();
		customer.setName("Curry");
		customer.setAge(28);
		customer.setCity("奧克蘭");
		
		session.save(customer);
		
		// 提交事務,釋放資源		
		transaction.commit();
		session.close();
		sessionFactory.close();
	}
console中自動生成的sql:


2) 使用 session對象 get或者load  完成根據 id 查詢
            (Customer) session.get(Customer.class, id);

測試代碼:

	@Test
	//根據ID查詢
	public void testFindById(){
		//實例化配置對象,加載配置文件hibernate.cfg.xml
		Configuration configuration = new Configuration().configure();
		//創建會話工廠
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		//創建會話
		Session session = sessionFactory.openSession();
		//開啓事務
		Transaction transaction = session.beginTransaction();
		
		int id = 1;
		Customer customer = (Customer) session.get(Customer.class, id);
		System.out.println(customer);
		
		//提交事務,釋放資源
		transaction.commit();
		session.close();
		sessionFactory.close();
	}
結果:


3)使用session對象 update方法 完成 修改操作

      (修改所有字段,如果不設置某個字段的值,則爲空;爲了解決這個問題,我們可以先從數據庫中查詢出來該對象,然後只修改其中一個字段,就達到了我們需要的效果)
      session.update(customer); 根據id修改其它所有字段內容 (防止修改爲null的情況)

	@Test
	public void testUpdate(){
		//實例化配置對象,加載配置文件hibernate.cfg.xml
		Configuration configuration = new Configuration().configure();
		//創建會話工廠
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		//創建會話
		Session session = sessionFactory.openSession();
		//開啓事務
		Transaction transaction = session.beginTransaction();
		
		Customer customer = new Customer();
		customer.setId(1);
		customer.setName("Curry");
		customer.setAge(28);
		customer.setCity("上海");
		
		session.update(customer);
		
		//提交事務,釋放資源
		transaction.commit();
		session.close();
		sessionFactory.close();
	}
測試結果:


4) 使用session對象 delete方法 完成 刪除操作 
      session.delete(customer); 根據id刪除

	@Test
	public void testDelete(){
		//實例化配置對象,加載配置文件hibernate.cfg.xml
		Configuration configuration = new Configuration().configure();
		//創建會話工廠
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		//創建會話
		Session session = sessionFactory.openSession();
		//開啓事務
		Transaction transaction = session.beginTransaction();
		
		Customer customer = new Customer();
		customer.setId(1);
		session.delete(customer);
		
		//提交事務,釋放資源
		transaction.commit();
		session.close();
		sessionFactory.close();
	}
測試結果:


5)  查詢所有數據 
      Session對象提供了兩個方法可以獲得Query對象 --- 完成查詢
      Query createQuery(String queryString)  接受HQL
      SQLQuery createSQLQuery(String queryString)  接受SQL
      * createQuery 返回Query對象,接收HQL查詢語言 (Hibernate Query Language ) ---- 特點:語法類似SQL,面向類和屬性的查詢 
      * 使用HQL查詢,面向類和屬性,生成底層SQL 返回結果 封裝類對象中
      * 使用SQL查詢,面向數據表,SQL無需生成,默認返回結果 每條記錄 Object[] ------- 通過 addEntity(Customer.class) 指定將返回數據封裝對象

HQL:

	@Test
	//查詢所有(HQL)
	public void testFindAllByHQL(){
		//實例化配置對象,加載配置文件hibernate.cfg.xml
		Configuration configuration = new Configuration().configure();
		//創建會話工廠
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		//創建會話
		Session session = sessionFactory.openSession();
		//開啓事務
		Transaction transaction = session.beginTransaction();
		
		//編寫hql(面向類和屬性的查詢)
		String hql = "from Customer";//這裏Customer是類名,查詢Customer類對應表所有數據
		Query query = session.createQuery(hql);
		List<Customer> list = query.list();
		System.out.println(list);
		
		//提交事務,釋放資源
		transaction.commit();
		session.close();
		sessionFactory.close();
	}
測試結果:


SQL:

	@Test
	//查詢所有(SQL)
	public void testFindAllBySQL(){
		//實例化配置對象,加載配置文件hibernate.cfg.xml
		Configuration configuration = new Configuration().configure();
		//創建會話工廠
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		//創建會話
		Session session = sessionFactory.openSession();
		//開啓事務
		Transaction transaction = session.beginTransaction();
		
		//編寫sql
		String sql = "select * from customer";
		SQLQuery sqlQuery = session.createSQLQuery(sql);
		sqlQuery.addEntity(Customer.class);//將查詢結果封裝到Customer類對象中
		List<Customer> list = sqlQuery.list();
		System.out.println(list);
		
		//提交事務,釋放資源
		transaction.commit();
		session.close();
		sessionFactory.close();
	}
測試結果:






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章