Hibernate框架之入門


1.Hibernate框架簡述

Hibernate的核心組件
在基於MVC設計模式的JAVA WEB應用中,Hibernate可以作為模型層/數據訪問層。它通過配置文件(hibernate.properties或hibernate.cfg.xml)和映射文件(***.hbm.xml)把JAVA對象或PO(Persistent Object,持久化對象)映射到數據庫中的數據庫,然后通過操作PO,對數據表中的數據進行增,刪,改,查等操作。
除配置文件,映射文件和持久化類外,Hibernate的核心組件包括以下幾部分:
a)Configuration類:用來讀取Hibernate配置文件,並生成SessionFactory對象。
b)SessionFactory接口:產生Session實例工廠。
c)Session接口:用來操作PO。它有get(),load(),save(),update()和delete()等方法用來對PO進行加載,保存,更新及刪除等操作。它是Hibernate的核心接口。
d)Query接口:用來對PO進行查詢操。它可以從Session的createQuery()方法生成。
e)Transaction接口:用來管理Hibernate事務,它主要方法有commit()和rollback(),可以從Session的beginTrancation()方法生成。

Persistent Object
持久化對象可以是普通的Javabeans,惟一特殊的是它們與(僅一個)Session相關聯。JavaBeans在Hibernate中存在三種狀態:
1.臨時狀態(transient):當一個JavaBean對象在內存中孤立存在,不與數據庫中的數據有任何關聯關系時,那么這個JavaBeans對象就稱為臨時對象(Transient Object)。
2.持久化狀態(persistent):當一個JavaBean對象與一個Session相關聯時,就變成持久化對象(Persistent Object)
3.脫管狀態(detached):在這個Session被關閉的同時,這個對象也會脫離持久化狀態,就變成脫管狀態(Detached Object),可以被應用程序的任何層自由使用,例如可以做與表示層打交道的數據輿對象(Data Transfer Object)。

Hibernate的運行過程
Hibernate的運行過程如下:
A:應用程序先調用Configration類,該類讀取Hibernate的配置文件及映射文件中的信息,並用這些信息生成一個SessionFactpry對象。
B:然后從SessionFactory對象生成一個Session對象,並用Session對象生成Transaction對象;可通過Session對象的get(),load(),save(),update(),delete()和saveOrUpdate()等方法對PO進行加載,保存,更新,刪除等操作;在查詢的情況下,可通過Session對象生成一個Query對象,然后利用Query對象執行查詢操作;如果沒有異常,Transaction對象將 提交這些操作結果到數據庫中。

Hibernate的運行過程如下圖:

2.入門案例

 01.准備各種jar包(我想就不用我教了吧)

 02.准備學生實體類(用於操作對應數據庫)   

package cn.zhang.entity;
//實體類
public class Student {
    
    private int stuno;
    
    private String stuname;
    
    private int stuage;
    
    private int stuid;
    
    private int stuseat;

    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Student(String stuname, int stuage, int stuid, int stuseat) {
        super();
        this.stuname = stuname;
        this.stuage = stuage;
        this.stuid = stuid;
        this.stuseat = stuseat;
    }

    public Student(int stuno, String stuname, int stuage, int stuid, int stuseat) {
        super();
        this.stuno = stuno;
        this.stuname = stuname;
        this.stuage = stuage;
        this.stuid = stuid;
        this.stuseat = stuseat;
    }


    public int getStuid() {
        return stuid;
    }
    
    public void setStuid(int stuid) {
        this.stuid = stuid;
    }



    public int getStuseat() {
        return stuseat;
    }



    public void setStuseat(int stuseat) {
        this.stuseat = stuseat;
    }



    public int getStuno() {
        return stuno;
    }

    public void setStuno(int stuno) {
        this.stuno = stuno;
    }

    public String getStuname() {
        return stuname;
    }

    public void setStuname(String stuname) {
        this.stuname = stuname;
    }

    public int getStuage() {
        return stuage;
    }

    public void setStuage(int stuage) {
        this.stuage = stuage;
    }

    
    
    

}

03.在src下設計Hibernate配置文件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">zhangzong</property>
        <property name="connection.password">123</property>

        <!-- SQL dialect (SQL 方言)-->
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
    
        <!-- Drop and re-create the database schema on startup -->
         <property name="hbm2ddl.auto">update</property> 

        <!-- Echo all executed SQL to stdout  在控制台打印后台的SQL語句-->
        <property name="show_sql">true</property>
        
        <!-- 格式化顯示SQL -->
        <property name="format_sql">true</property>    
        
        <!-- JDBC connection pool (use the built-in) -->
        <!-- <property name="connection.pool_size">1</property> -->
        
        <!-- Enable Hibernate's automatic session context management -->
        <!--  <property name="current_session_context_class">thread</property> -->
        
        <!-- Disable the second-level cache -->
        <!-- <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>-->

        <mapping resource="cn/zhang/entity/Student.hbm.xml" />

    </session-factory>

</hibernate-configuration>

04.在實體類下設計映射文件Student.hbm.xml(在配置文件hibernate.cfg.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="cn.zhang.entity">
        <class name="Student" table="stuinfo">
        <id name="stuno" column="stuno">
           <!-- 主鍵生成策略:native:
           native:如果后台是Oracle  
                      后台是MySQL,自動應用自增 -->
            <generator class="native"/>
        </id>
        <property name="stuname" type="string" column="stuname"/>
        <property name="stuage"/>
        
        <property name="stuid" type="int" column="stuid"/>
        <property name="stuseat"/>
    </class>
       
</hibernate-mapping>

05.添加測試類

001.更新(新增)一個學生記錄

package cn.zhang.test;
//新增一條數據
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import cn.zhang.entity.Student;

public class InsertTest {
    
    public static void main(String[] args) {
        //准備對象
        Student student=new Student("光衣", 12,112333,2);//Student.hbm.xml已配置編號為自增,所以這里不用添加編號了
         //讀取大配置文件,獲取要連接的數據庫信息
        Configuration configuration=new Configuration().configure();
         //創建SessionFactory
        SessionFactory factory = configuration.buildSessionFactory();
        //加工session
        Session openSession = factory.openSession();
        
        Transaction beginTransaction = openSession.beginTransaction();
        openSession.save(student);
        
        beginTransaction.commit();
        
        System.out.println("成功");

    }

}

002.修改一個學生信息

package cn.zhang.test;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import cn.zhang.entity.Student;

public class UpdateTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        //1.讀取大配置文件,獲取要連接的數據庫信息
        Configuration conf=new Configuration().configure();
        //2.創建SessionFactory
        SessionFactory factory =conf.buildSessionFactory();
        //3加工session
        Session session = factory.openSession();
        Transaction tx=session.beginTransaction();
        //獲取對象
        Student stu =new Student(1,"光衣", 12,112333,2);
        //更新
        session.update(stu);
        //提交事務
        tx.commit();
        System.out.println("更新成功");


    }

}

003.刪除一個指定學生信息

package cn.zhang.test;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import cn.zhang.entity.Student;
public class DeleteTest {
    
    public static void main(String[] args) {
        //1.讀取大配置文件,獲取要連接的數據庫信息
        Configuration conf=new Configuration().configure();
        //2.創建SessionFactory
        SessionFactory factory =conf.buildSessionFactory();
        //3.加工session
        Session session = factory.openSession();
        
        Transaction tx=session.beginTransaction();
        //獲取對象
        Student stu =new Student();
        stu.setStuno(3);//指定要刪除的編號
        //刪除指定
        session.delete(stu);
        //提交事務
        tx.commit();
        System.out.println("刪除成功");

    }

}

 004.查詢一個指定學生信息

package cn.zhang.test;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import cn.zhang.entity.Student;

public class SelectTest {

    public static void main(String[] args) {
        //1.讀取大配置文件,獲取要連接的數據庫信息
        Configuration conf=new Configuration().configure();
        //2.創建SessionFactory
        SessionFactory factory =conf.buildSessionFactory();
        //3.打開session
        Session session = factory.openSession();
        //4.加載數據操作
           //如果表中沒有你指定的主鍵列,get()方法的是null
        Student student =(Student)session.get(Student.class, 4); 
           //如果表中沒有你指定的主鍵列,程序運行到student.getStuname()時會拋出異常
       //Student student =(Student)session.load(Student.class, 4);
        //5.輸出數據
        System.out.println(student.getStuname());
        //6.關閉session
        session.close();
        
        

    }

}

 

 

    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM