1. 程式人生 > >Hibernate專案簡單配置

Hibernate專案簡單配置

Hibernate專案配置

作為一個優秀的持久層框架Hibernate很容易入門。在使用Hibernate框架前,先來看看Hibernate是如何實現ORM框架的,即Hibernate的執行流程,如圖所示:

現在開始新建我們的第一個Hibernate專案

1.在Eclipse中建立Web專案,名稱為HibernateConfigure

2. 將下載下來的Hibernate框架E:\hibernate-release-5.2.9.Final\lib\required中的jar包複製貼上到WEB-INF\lib目錄下

3.把資料庫驅動包複製貼上到WEB-INF\lib
目錄下(比如我的是Oracle資料庫,版本為11g,驅動jar包為ojdbc,MySQL資料庫則用mysql-connector-java)

Hibernate架包

4.建立實體類。在src目錄下新建com.skt.entity包,並在其中建立實體類UserTest(對應資料庫表user_test,沒有的話自己新建一個表,欄位自己隨便設兩個)。Users類包含一些屬性(對應資料表user_test欄位),以及與之對應的getXXX()和setXXX()方法,還包括無參構造方法。

package com.skt.entity;

public class UserTest {

    private Integer id;
    private
String userName; private String pwd; private String phone; private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName
(String userName) { this.userName = userName; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public UserTest() { } }

5.編寫對映檔案 UserTest.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2017-10-14 12:46:14 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.skt.entity.UserTest" table="USER_TEST">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="sequence">
                <param name="sequence_name">SEQ_USER_TEST</param>
            </generator>
        </id>
        <property name="userName" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="pwd" type="java.lang.String">
            <column name="PASSWORD" />
        </property>
        <property name="phone" type="java.lang.String">
            <column name="PHONE" />
        </property>
        <property name="email" type="java.lang.String">
            <column name="EMAIL" />
        </property>
    </class>
</hibernate-mapping>

6.編寫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>
  <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.password">123456</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
  <property name="hibernate.connection.username">MKYDY</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>

  <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

  <!-- 執行過程中將sql語句打印出來,建議在開發階段將其設定為true -->
  <property name="show_sql">true</property>
  <!-- 根據配置檔案更新資料庫欄位
        create:重新建表
        create-drop:刪除表,再建表
        update:更新表
        none:不對錶操作
         -->
  <property name="hbm2ddl.auto">none</property>

  <mapping resource="com/skt/entity/UserTest.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

7. 編寫Hbernate工具類HibernateUtil

package com.skt.util;

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

/**
 * Hibernate工具類
 * @author JackerMkydy
 *
 */
public class HibernateUtil {

    private static SessionFactory sessionFactory;  
    // 建立執行緒區域性變數threadLocal,用來儲存Hibernate的Session  
    private static final ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();  
    // 使用靜態程式碼塊初始化Hibernate  
    static  
    {  
        try  
        {  
            // 讀取配置檔案  
            Configuration cfg = new Configuration().configure();  
            // 建立SessionFactory  
            sessionFactory = cfg.buildSessionFactory();  
        }catch(Throwable ex)  
        {  
            throw new ExceptionInInitializerError(ex);  
        }  
    }  
    // 獲得SessionFactory的例項  
    public static SessionFactory getsSessionFactory()  
    {  
        return sessionFactory;  
    }  
    // 獲得ThreadLocal物件管理的Session  
    public static Session getsSession() throws HibernateException  
    {  
        Session session=(Session) threadLocal.get();  
        if(session==null||!session.isOpen())  
        {  
            if(sessionFactory==null)  
            {  
                rebuildSessionFactory();  
            }  
            // 通過SessionFactory物件建立Session物件  
            session=(sessionFactory!=null)?sessionFactory.openSession():null;  
            // 將Session物件儲存到執行緒區域性變數threadLocal中  
            threadLocal.set(session);  
        }  
        return session;  
    }  
    // 關閉Session例項  
    public static void closeSession()  
    {  
        // 從執行緒區域性變數threadLocal中獲取之前存入的Session例項  
        Session session=(Session)threadLocal.get();  
        threadLocal.set(null);  
        if(session!=null)  
        {  
            session.close();  
        }  
    }  
    // 重建SessionFactory  
    public static void rebuildSessionFactory()  
    {  
        Configuration configuration=new Configuration();  
        configuration.configure("/hibernate.cfg.xml");  
        sessionFactory=configuration.buildSessionFactory();  
    }  
    // 關閉快取和連線池  
    public static void shutdown()  
    {  
        getsSessionFactory().close();  
    } 
}

或者

package com.hb.util;

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

/**
 * HibernateUtil 封裝session相關內容
 * @author oracle
 */
public class HibernateUtil
{
    // sessionFactory
    private static SessionFactory sessionFactory;

    /**
     * 獲取SessionFactory
     * @return SessionFactory
     */
    public static SessionFactory getSessionFactory()
    {
        try
        {
            // sessionFactory為空時,就重新建立
            if (sessionFactory == null)
            {
                Configuration configuration = new Configuration();
                sessionFactory = configuration.configure().buildSessionFactory();
            }
        }
        catch (Throwable ex)
        {
            ex.printStackTrace();
        }
        return sessionFactory;
    }

    // 定義session
    @SuppressWarnings("rawtypes")
    public static final ThreadLocal session = new ThreadLocal();

    /**
     * 獲取當前session
     * @return session
     */
    @SuppressWarnings("unchecked")
    public static Session currentSession()
    {
        Session s = (Session) session.get();
        if (s == null)
        {
            s = getSessionFactory().openSession();
            session.set(s);
        }
        return s;
    }

    /**
     * 關閉session
     * @throws HibernateException 異常
     */
    @SuppressWarnings("unchecked")
    public static void closeSession() throws HibernateException
    {
        Session s = (Session) session.get();
        session.set(null);
        if (s != null)
        {
            s.close();
        }
    }

}

8.編寫測試類TestUser

package com.skt.test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.skt.entity.UserTest;
import com.skt.util.HibernateUtil;

/**
 * 測試類,增,刪,改,查
 * @author oracleOAEC11
 *
 */
public class TestUser {

    /**
     * 新增使用者
     */
    public void addUser() {
        //建立實體類(瞬態物件)
        UserTest ut = new UserTest();
        ut.setEmail("[email protected]");
        ut.setPhone("1987445345");
        ut.setPwd("111111");
        ut.setUserName("Tom");
        //獲得Session物件
        Session session = HibernateUtil.getsSession();
        //獲得Transaction例項 
        Transaction tc = session.beginTransaction();
        try {
            // 使用Session的save方法將持久化物件儲存到資料庫  
            session.save(ut);
            // 提交事務  
            tc.commit();
        } catch (Exception e) {
            e.printStackTrace();
            // 出現異常,回滾事務  
            tc.rollback(); 
        }finally {
            // 關閉Session連線 
            HibernateUtil.closeSession();
        }

    }

    /**
     * 查詢使用者
     */
    public void getUser() {
        UserTest ut = null;
        Session session = HibernateUtil.getsSession();  
        Transaction tx = session.beginTransaction();
        try {
            // 使用session的get方法獲取指定id的使用者 
            ut = session.get(UserTest.class, 2);
            System.out.println(ut.getUserName()+":"+ut.getEmail());
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeSession();
        }
    }

    /**
     * 刪除使用者
     */
    public void deleteUser() {
        Session session = HibernateUtil.getsSession();  
        Transaction tx = session.beginTransaction();
        try {
            // 使用session載入一個持久化物件 
            UserTest ut = session.get(UserTest.class, 3);
            session.delete(ut);
            System.out.println(ut.getUserName()+":"+ut.getEmail());
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeSession();
        }
    }

    /**
     * 更新使用者資料
     */
    public void updateUser() {
        Session session = HibernateUtil.getsSession();  
        Transaction tx = session.beginTransaction();  
        try {  
            // 使用session的update方法更新持久化物件 
            UserTest ut = session.get(UserTest.class, 2);
            ut.setUserName("Alice");
            session.update(ut);  
            tx.commit();  
        } catch (Exception e) {  
            tx.rollback();  
            e.printStackTrace();
        } finally {  
            HibernateUtil.closeSession();  
        }  
    }

    public static void main(String[] args) {
        TestUser tu = new TestUser();
        tu.updateUser();
    }
}

這裡寫圖片描述
到此,一個簡單的Hibernate專案就搭建完成了。

Hibernate提供了一些常用的主鍵生成器策略,如下:

  • increment
  • identity
  • sequence
  • hilo
  • native
  • assigned
    具體的主鍵生成器策略有何作用這裡就不多說了,如果要看請移步starskyhu

途中遇到的問題和犯得錯誤:

  • 資料表沒有序列化導致異常
  • UserTest.hbm.xml中id主鍵生成策略用了native報異常:序列不存在,網上查找了一下,說是oracle 資料庫插入資料不能自增,可以建立sequence生成自增序列(還是一臉慒逼)
  • 用Hibernate自動生成的hibernate.cfg.xml配置檔案中<session-factory name="">需要把name=""去掉
  • Disabling contextual LOB creation as createClob() method threw error:java.lang.reflect.InvocationTargetException,專案執行正常,又去網上百度了一波,
    有兩種說法:

    • 一種是說Oracle資料庫驅動版本的原因(過老?)
    • 還有一種說法是(搞得我還是一頭霧水):It happens during the boot, when Hibernate tries to retrieve some meta information from the database我英語不太好,但大概的意思就是當Hibernate試圖從資料庫檢索一些元資料資訊的時候發生了此異常。他們給出瞭解決方法: 在hibernate.cfg.xml檔案中新增以下屬性<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
  • Hibernate的github地址:Hibernate

總結

通過對本次的專案配置,對Hibernate框架有了更清晰的瞭解,但還有許多知識等待擴充,但從各種異常當中也收穫許多。不要怕異常,只有在失敗中才能加深自己對這框架的理解和使用。接下來的一段時間裡 讓我們一起努力吧!

相關推薦

Hibernate專案簡單配置

Hibernate專案配置 作為一個優秀的持久層框架Hibernate很容易入門。在使用Hibernate框架前,先來看看Hibernate是如何實現ORM框架的,即Hibernate的執行流程,如圖所示: 現在開始新建我們的第一個H

Maven專案簡單配置Log4j

一, 在pom.xml中新增如下依賴 <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <versi

spring hibernate listener 簡單配置

一、springXML配置檔案 <?xml version="1.0" encoding="UTF-8"?> <beans     xmlns="http://www.springframework.org/schema/beans"     xmlns:

hibernate簡單配置和使用

Hibernate的作用: 這個是Hibernate的一個簡單結構。 Hibernate是一款持久化框架(ORM)即Object Relationship Mapping,對JDBC進行了輕量級的封裝,他能夠自動根據我們的需求,能夠將我們的實體類對映到資料庫表

Intellij Idea 15 下新建 Hibernate 專案以及如何新增配置

Hibernate學習:Intellij IDEA下新建Hibernate HelloWorld:Hibernate是java領域的一款輕量級ORM(物件關係模型)框架,它對JDBC進行了封裝,實現了從關係型資料庫到面向物件的領域模型的對映,可以將物件自動對映成資料庫中的資訊。它還提供了面向物件的資料

springboot多環境專案打包簡單配置

基類pom中配置如下 <profiles> <profile> <id>dev</id> <activation> <acti

如何獲取web專案hibernate.cfg.xml配置檔案中的資料

有時候想要獲取hibernate.cfg.xml配置檔案中的資料,網路上有很多方法,有的很複雜,這裡我介紹一種很簡單的獲取方法。 hibernate.cfg.xml配置檔案中有連線資料庫所需的各種資訊,比如這裡要獲取connection.url欄位對應的url資料,如下所示

一個專案hibernate框架下配置多個數據庫

hibernate框架下配置多個數據庫 當我們在同一個專案中需要同時連線多個數據庫時,在hibernate框架下的我們可以通過配置多個sessionFactory與多個連線池配置實現獲取不同資料庫的連線session物件。 初始化hibernate的se

用Idea 開發一個簡單的Struts2+Maven+Hibernate 專案的流程

本文整理了用Idea Intellij 開發一個綜合運用Strut 2, Maven 和Hibernate 專案的流程,並在步驟中對比了此專案技術相對於Servlet、手動新增Jar 和JDBC 的優勢,還記錄了一些可能出現問題的坑,最後總結專案收到請求後的執行過程。1)Fi

SpringBoot簡明教程之專案屬性配置(二):@ConfigurationProperties與@Value簡單比較

前文回顧 在上一篇博文:SpringBoot簡明教程之專案屬性配置(一):YAML簡介 中我們簡單的介紹了SpringBoot的專案屬性配置中有關YAML檔案的簡單語法以及簡單展示了通過配置檔案進行值注入。 @ConfigurationProper

建立簡單hibernate專案步驟

(1)new -- javaproject--輸入專案名稱  (與web沒有關係,只與jdbc有關係的) (2)新增資料庫。首先顯示, windows--show views--other-- 選

IntelliJ IDEA 最簡單配置搭建Spring MVC Java web Maven專案

原文地址:http://blog.csdn.net/qq_27093465/article/details/68961393 使用這個IntelliJ IDEA建立一個簡單的Java web maven專案,我在前面的文章裡面已經示範過了。 先看下專案目錄

Hibernate學習筆記(二)——建立一個簡單Hibernate專案

首先來看看Hibernate開發的一個簡單流程: (1)準備開發環境,建立Hibernate專案。 (2)在資料庫中建立資料表。 (3)建立持久化類。 (4)設計對映檔案,使用Hibernate對映檔案將POJO物件對映到資料庫。 (5)建立Hibernate的配置檔

【ADO.NET】1、簡單配置與使用

字符串 文件中 .exe 增加 獲取字符串 pass 數據庫連接 rect manage 1、一些基礎的知識點 ExecuteReader(); //返回查詢到的數據,一次一行,用於 selectExecuteNonQuery(); //返回影響的行數,用於 delete,

hibernate框架中配置顯示sql語句

per 控制 col property hiberna color sql 輸出 最好 使用Hibernate的框架開發時,可在Hibernate.cfg.xml中加上 <property name="hibernate.show_sql">true<

phpstorm一些簡單配置

行間距 com pst -1 設置 mage ges tro .com   1.字體大小和行間距      2.設置編碼:包括編輯工具編碼和項目編碼    phpstorm一些簡單配置

httpd.conf簡單配置

ftw ati c11 註意 情況 混淆 可能 con eve 本文介紹apache中httpd.conf的配置。該配置也可解決打開php文件卻變成下載的尷尬情況 1 修改網站根目錄查找DocumentRoot有這麽一行DocumentRoot "C:/Program

Jenkins一些簡單配置配置Maven國內鏡像倉庫

jenkins maven國內鏡像 最近在阿裏雲申請一臺雲主機測試Jenkins + Maven自動化持續部署,在構建過程中經常進程自動退出;由於申請測試的免費雲主機配置較低,所以每次在構建的時候會發現訪問主機就會變得很卡,最後進程退出。Jenkins權威指南文中描述: 持續集成服務器會使用很多內

ftp服務器的簡單配置使用

配置使用 服務 簡單配置 ftpd systemctl install vsftp art tp服務器 yum install -y vsftpd systemctl start vsftpd cd /var/ftp/pub/ mkdir 111 touch w

CxImage 簡單配置與使用

選項 ghost reel sage header ctu 也會 wim 才會 CxImage 簡單配置與使用 如果本篇文章還不能解決你在生成解決方案以及便宜過程中的問題 請參閱: http://blog.csdn.net/afterwards_/article/det