有關Spring的知識大部分都已經溫習完畢,今天開始轉向Hibernate的溫習工作了
必須包hibernate-distribution-3.5.3-Final\hibernate3.jar
hibernate-distribution-3.5.3-Final\lib\required\slf4j-api-1.5.8.jar
hibernate-distribution-3.5.3-Final\lib\required\slf4j-api-1.5.8.jar
hibernate-distribution-3.5.3-Final\lib\required\slf4j-api-1.5.8.jar
hibernate-distribution-3.5.3-Final\lib\required\slf4j-api-1.5.8.jar
hibernate-distribution-3.5.3-Final\lib\required\slf4j-api-1.5.8.jar
首先在hibernate資源包中找到:hibernate-distribution-3.5.3-Final\project\tutorials\web\src\main\resources\hibernate.cfg.xml,將這個配置文件複製到你的項目SRC目錄下,然後根據實際情況進行適當修改,我的示例中修改後爲
- <span style="font-size: large;"><span style="font-size: large;"><?xml version="1.0" encoding="utf-8" ?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://hibernate.sourceforge.net/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:///test</property>
- <property name="connection.username">root</property>
- <property name="connection.password">root</property>
- <!--JDBC連接池大小-->
- <property name="connection.pool_size">2</property>
- <!-- 數據庫語言 -->
- <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
- <!-- Hibernate當前的會話上下文 -->
- <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>
- <!-- 禁用二級緩存 -->
- <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
- <!-- 控制檯顯示SQL語句 -->
- <property name="show_sql">true</property>
- <!-- 格式化SQL語句 -->
- <property name="hibernate.format_sql">true</property>
- <!--
- 啓動時刪數據庫中的表,然後創建,退出時不刪除數據表
- <property name="hbm2ddl.auto">create</property>
- -->
- <!--
- 啓動時刪數據庫中的表,然後創建,退出時自動刪除所有表
- <property name="hbm2ddl.auto">create-drop</property>
- -->
- <!--
- 自動修改,如果表結構與實體類不一致,那麼就更新表結構,數據會保留
- (如果原表不存在,就創建新表;如果缺少相應的字段,就加入;對於原來存在的多餘字段,不作處理)
- <property name="hbm2ddl.auto">update</property>
- -->
- <!--
- 自動校驗,如果表結構與實體類不一致,那麼不做任何操作,報錯
- <property name="hbm2ddl.auto">validate</property>
- -->
- <!-- Drop and re-create the database schema on startup -->
- <property name="hbm2ddl.auto">create</property>
- <!-- 實體關係映射文件 -->
- <mapping resource="com/javacrazyer/domain/Student.hbm.xml"/>
- </session-factory>
- </hibernate-configuration></span></span>
數據庫方言一定要設定對,跟數據庫驅動匹配org.hibernate.dialect.MySQLDialect
否則的話就會出現下面這個錯誤
- <span style="font-size: large;"><span style="font-size: large;">Unknown table 'system_sequences' in information_schema</span></span>
其次,看看實體類Student.java
- <span style="font-size: large;"><span style="font-size: large;">package com.javacrazyer.domain;
- import java.util.Date;
- /**
- * 學生實體類 --> 按JavaBean的形式定義
- *
- */
- public class Student {
- private int id; //OID 對象標識符
- private String name;
- private int age;
- private boolean gender;
- private Date birthday;
- private double score;
- 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 boolean isGender() {
- return gender;
- }
- public void setGender(boolean gender) {
- this.gender = gender;
- }
- public Date getBirthday() {
- return birthday;
- }
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
- public double getScore() {
- return score;
- }
- public void setScore(double score) {
- this.score = score;
- }
- @Override
- public String toString(){
- return "id=" + id + ",name=" + name + ",gender=" + gender + ",age=" + age
- + ",birthday=" + this.birthday + ",score=" + score;
- }
- }</span></span>
實體關係映射文件Student.hbm.xml,具體內容也可以參照hibernate資源包下:
hibernate-distribution-3.5.3Final\project\tutorials\web\src\main\resources\org\hibernate\tutorial\
domain\Person.hbm.xml
那麼進行修改後的內容爲
- <span style="font-size: large;"><span style="font-size: large;"><?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
- <hibernate-mapping>
- <class name="com.javacrazyer.domain.Student" table="student">
- <id name="id" column="id">
- <generator class="native"/>
- </id>
- <property name="name" column="name"/>
- <property name="age"/>
- <property name="gender"/>
- <property name="birthday"/>
- <property name="score"/>
- </class>
- </hibernate-mapping></span></span>
現在介紹下hbm.xml映射文件中各種屬性的介紹吧
1.class 節點
name: 類名
table: 類對應表名,默認爲類名稱
dynamic-update: 生成更新字段時,只包含發生變動的字段,默認爲false。
dynamic-insert: 生成insert語句時僅包含非null字段
Proxy: 代理類,默認爲空
discriminator-value: 子類辨別標識用於多態支持
where: 通過限定條件查詢結果集。如:查詢有籍在校學生的信息可以使用"where studentstatus='0'"
2.id節點
1.column 字段名稱
2.type 字段類型
3.length 字段長度
4.unsaved-value 用於判斷對象值是否已經保存
5.generator-class 主鍵產生方式
assigned
hilo
seqhilo
increment
identity
sequence
native
uuid.hex
uuid.string
foreign
---------------------------------------------------------------------------------------------------------------
主鍵產生方式說明
increment(遞增)
用於爲long, short或者int類型生成唯一標識。只有在沒有其他進程往同一張表中插入數據時才能使用。 在集羣下不要使用。
identity
對DB2,MySQL, MS SQL Server, Sybase和HypersonicSQL的內置標識字段提供支持。返回的標識符是long, short 或者int類型的。
sequence (序列)
在DB2,PostgreSQL, Oracle, SAP DB, McKoi中使用序列(sequence),而在Interbase中使用生成器(generator)。返回的標識符是long, short或者 int類型的。
hilo (高低位)
使用一個高/低位算法來高效的生成long, short或者 int類型的標識符。給定一個表和字段(默認分別是是hibernate_unique_key 和next_hi)作爲高位值得來源。高/低位算法生成的標識符只在一個特定的數據庫中是唯一的。在使用JTA獲得的連接或者用戶自行提供的連接中,不要 使用這種生成器。
seqhilo(使用序列的高低位)
使用一個高/低位算法來高效的生成long, short或者 int類型的標識符,給定一個數據庫序列(sequence)的名字。
uuid.hex
用一個128-bit的UUID算法生成字符串類型的標識符。在一個網絡中唯一(使用了IP地址)。UUID被編碼爲一個32位16進制數字的字符串。
uuid.string
使用同樣的UUID算法。UUID被編碼爲一個16個字符長的任意ASCII字符組成的字符串。不能使用在PostgreSQL數據庫中
native(本地)
根據底層數據庫的能力選擇identity, sequence 或者hilo中的一個。
assigned(程序設置)
讓應用程序在save()之前爲對象分配一個標示符。
foreign(外部引用)
-------------------------------------------------------------------------------------------------------------------------
3.property 節點
1.column 數據庫表字段名稱
2.type 類型
3.length 長度
4.not-null 字段是否允許爲空
5.unique 字段是否允許唯一(是否允許重複值)
6.insert insert操作時,是否允許包含本字段數值
7.update update操作時,是否包含本字段數據
特別說明
現在有個問題,按平常思路就是,得在數據庫中創建一個student表吧,字段及類型得與Student類吻合,其實不用,爲什麼這麼說,因爲在hibernate.cfg.xml中 <property name="hibernate.hbm2ddl.auto">update</property>這句話配置的值爲update就表示沒有表的情況下會在執行數據庫操作前自動創建數據庫表,這下就省了好多事了
不過,如果你非要手工去創建,寫SQL語句在數據庫工具中也沒必要,hibernate有相應的API支持你生成對應的數據庫表
下面這個類就就可以
創建數據庫表的類DBScriptExport .Java
- <span style="font-size: large;"><span style="font-size: large;">package com.javacrazyer.common;
- import org.hibernate.cfg.Configuration;
- import org.hibernate.tool.hbm2ddl.SchemaExport;
- /**
- * 根據對象關係映射文件直接生成數據庫表或生成建表的腳本
- *
- */
- public class DBScriptExport {
- public static void main(String[] args) {
- export2File("dbcript.sql");
- }
- public static void export2DB(){
- //加載Hibernate的全局配置文件
- Configuration config = new Configuration().configure();
- SchemaExport export = new SchemaExport(config);
- export.create(true, true);
- }
- public static void export2File(String dest){
- Configuration config = new Configuration().configure();
- SchemaExport export = new SchemaExport(config);
- export.setOutputFile(dest)
- .setDelimiter(";")
- .setFormat(true)
- .create(true, false);
- }
- }
- </span></span>
獲取session的HibernateUtil.java
- <span style="font-size: large;"><span style="font-size: large;">package com.javacrazyer.common;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- /**
- * Hibernate工具類
- *
- */
- public class HibernateUtil {
- private static final SessionFactory factory;
- private HibernateUtil(){}
- static{
- //加載Hibernate全局配置文件,根據配置信息創建SessionFactory工廠實例
- factory = new Configuration().configure().buildSessionFactory();
- }
- public static SessionFactory getSessionFactory(){
- return factory;
- }
- public static Session getSession(){
- return factory.openSession();
- }
- }
- </span></span>
最後的測試類HibernateTest.java
- <span style="font-size: large;"><span style="font-size: large;">package com.javacrazyer.test;
- import java.util.Date;
- import java.util.List;
- import org.hibernate.Criteria;
- import org.hibernate.HibernateException;
- import org.hibernate.Query;
- import org.hibernate.Session;
- import org.hibernate.Transaction;
- import org.hibernate.criterion.Order;
- import org.junit.Assert;
- import org.junit.Test;
- import com.javacrazyer.common.HibernateUtil;
- import com.javacrazyer.domain.Student;
- /**
- * 使用Hibernate API完成CRUD
- * 更復雜的持久化操作需要使用到Query接口
- *
- */
- public class HibernateTest {
- @Test
- public void testAdd(){
- Student stu = new Student();
- stu.setName("test");
- stu.setBirthday(new Date());
- stu.setAge(1);
- stu.setGender(true);
- stu.setScore(66.8);
- //利用工廠打開一個Session實例
- Session session = HibernateUtil.getSession();
- //開啓一個操作事務
- Transaction tx = session.beginTransaction();
- //利用session進行持久化操作
- session.save(stu);
- //提交事務
- tx.commit();
- //關閉Session
- session.close();
- }
- @Test
- public void getStu(){
- //持久化管理器
- Session session = null;
- Transaction tx = null;
- try{
- session = HibernateUtil.getSession();
- tx = session.beginTransaction();
- //根據ID查詢實體對象
- Student stu = (Student)session.get(Student.class, 1);
- Assert.assertNotNull(stu);
- System.out.println(stu);
- tx.commit();
- }catch(HibernateException he){
- he.printStackTrace();
- tx.rollback();
- }finally{
- if(null != session && session.isOpen()){
- try{
- session.close();
- }catch(HibernateException e){
- e.printStackTrace();
- }
- }
- }
- }
- @Test
- public void testUpdate(){
- Session session = null;
- try{
- session = HibernateUtil.getSession();
- session.beginTransaction();
- Student stu = (Student)session.get(Student.class, 1);
- stu.setName("zs");
- stu.setScore(52.1);
- session.update(stu);
- session.getTransaction().commit();
- }catch(HibernateException e){
- Assert.fail();
- e.printStackTrace();
- session.getTransaction().rollback();
- }finally{
- if(session != null && session.isOpen()){
- session.close();
- }
- }
- }
- @Test
- public void testDelete(){
- Session session = null;
- try{
- session = HibernateUtil.getSession();
- //session.beginTransaction();
- Student stu = (Student)session.get(Student.class, 2);
- System.out.println(stu);
- session.delete(stu);
- //session.getTransaction().commit();
- }catch(HibernateException e){
- Assert.fail();
- e.printStackTrace();
- //session.getTransaction().rollback();
- }finally{
- if(session != null && session.isOpen()){
- session.close();
- }
- }
- }
- @Test
- public void testGet(){
- Session session = null;
- try{
- session = HibernateUtil.getSession();
- session.beginTransaction();
- Student stu = (Student)session.get(Student.class, 2);
- System.out.println(stu);
- Student stu2 = (Student) session.get(Student.class, 2);
- System.out.println(stu2);
- session.getTransaction().commit();
- }catch(HibernateException e){
- Assert.fail();
- e.printStackTrace();
- session.getTransaction().rollback();
- }finally{
- if(session != null && session.isOpen()){
- session.close();
- }
- }
- }
- @Test
- public void testGet2(){
- Session session = null;
- session = HibernateUtil.getSession();
- session.beginTransaction();
- Student stu = (Student)session.get(Student.class, 2);
- System.out.println(stu);
- session.getTransaction().commit();
- session.close();
- session = HibernateUtil.getSession();
- session.beginTransaction();
- Student stu2 = (Student) session.get(Student.class, 2);
- System.out.println(stu2);
- session.getTransaction().commit();
- session.close();
- }
- @SuppressWarnings("unchecked")
- @Test
- public void testQuery(){
- Session session = null;
- try{
- session = HibernateUtil.getSession();
- session.beginTransaction();
- Query query = session.createQuery("from Student");
- List<Student> stus = query.list();
- for(Student stu : stus){
- System.out.println(stu);
- }
- session.getTransaction().commit();
- }catch(HibernateException e){
- e.printStackTrace();
- session.getTransaction().rollback();
- }finally{
- if(session != null && session.isOpen()){
- session.close();
- }
- }
- }
- @SuppressWarnings("unchecked")
- @Test
- public void testCriteria(){
- Session session = null;
- try{
- session = HibernateUtil.getSession();
- session.beginTransaction();
- Criteria criteria = session.createCriteria(Student.class);
- List<Student> stus = criteria.addOrder(Order.desc("id")).list();
- for(Student stu : stus){
- System.out.println(stu);
- }
- session.getTransaction().commit();
- }catch(HibernateException e){
- e.printStackTrace();
- session.getTransaction().rollback();
- }finally{
- if(session != null && session.isOpen()){
- session.close();
- }
- }
- }
- }</span></span>
補充說明:
如果在hibernate.cfg.xml中配置的是
<property name="hibernate.hbm2ddl.auto">create</property>
這種配置前提是表已經存在
在這種情況下,只要你在項目的src下新建一個文件夾命名爲import.sql,並且裏面寫上數據庫插入語句,那麼就會執行插入操作,爲什麼只是插入,這得跟create值的這種創建啊方式有關,它是啓動hibernate時先刪除已存在的表,後新建表,新建的表本身就是空的,當然只能進行插入操作了
import.sql
- <span style="font-size: large;">insert into student(name,age,gender,birthday,score) values('test2',10,false,now(),11.2);</span>