標籤:
Hibernate架構
今天我來主要講一下Hibernate架構的配置步驟,在講之前,我們先瞭解一下使用架構的優勢
1.不再考慮公用問題,架構已經幫我們做好了
2.可以專心於商務邏輯,保證核心商務邏輯的開發品質
3.結構統一,便於學習和維護
4.架構中整合了前人的經驗,可以協助新手寫出穩定、效能優良而且結構優美的高品質程式。
我們都知道SSH整合架構指的是基於Struts或Struts2+Spring+Hibernate的技術架構,也就是我們常說的三大架構,使用這個整合架構將使我們應用程式更加健壯、穩固、輕巧和優雅。
Hibernate是資料持久化(資料持久化就是將記憶體中的資料模型轉換為儲存模型,以及將儲存模型轉換為記憶體... 然後根據架構的設定檔,自動或手動決定什麼時候把這種儲存提交到資料庫)工具,是一個開放原始碼的對象關係映射架構。
優點:
1.Hibernate功能強大,較之JDBC方式操作資料庫,代碼量大大減少,提高持久化代碼的開發速度,降低維護成本。
2.Hibernate支援許多物件導向的特性
3.可移植性好
4.Hibernate架構開源免費
缺點:
1.不適合以資料為中心的大量使用預存程序的應用。
2.大規模的批量插入、修改和刪除不適合用HibernateHibernate環境搭建
1.下載和部署jar包
2.建立設定檔hibernate.cfg.xml
<?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> <!-- Database connection settings 資料庫連接配置--> <property name="connection.driver_class">oracle.jdbc.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <property name="connection.username">wth</property> <property name="connection.password">1509184562</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect 方言--> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <!-- Echo all executed SQL to stdout 在控制台列印多工緩衝sql語句--> <property name="show_sql">true</property> <!-- 格式化語句 --> <property name="format_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <!-- 關聯小配置 --> <mapping resource="cn/entity/student.hbm.xml" /> </session-factory></hibernate-configuration>
3.建立持久化類和對應檔
小配置:
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.entity"> <class name="Student" table="STUDENT"> <id name="sId" column="SID"> <generator class="native"/> </id> <!-- assigned 程式員賦值 native後台DB賦值--> <property name="sName" type="string" column="SNAME"/> <property name="sAge"/> </class></hibernate-mapping>
持久化類
package cn.test;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.hibernate.classic.Session;import cn.entity.Student;public class Test { public static void main(String[] args) { Student stu=new Student(); stu.setsName("呵"); stu.setsAge(12); Configuration cfg=new Configuration().configure(); SessionFactory sc = cfg.buildSessionFactory(); Session se = sc.openSession(); Transaction tx=se.beginTransaction(); se.save(stu); tx.commit(); System.out.println("success!!!"); }}
我的第一個用Hibernate架構寫的小例子