史上最簡單的Hibernate入門簡單介紹

來源:互聯網
上載者:User

標籤:des   http   io   os   ar   使用   java   for   sp   

事實上Hibernate本身是個獨立的架構,它不須要不論什麼web server或application server的支援。然而,大多數的Hibernate入門介紹都加入了非常多非Hibernate的東西,比方: Tomcat, Eclipse, Log4J,Struts, XDoclet, 甚至JBoss。這easy讓人產生Hibernate複雜難懂的誤解,特別是打擊了剛開始學習的人的積極性。

在這篇文章將不涉及Eclipse, log4j, Struts, Tomcat, XDoclet,和JBoss。本文的目的是示範一下Hibernate的安裝過程以及最主要的功能,從而給剛開始學習的人一個低得不能再低的入門門檻。


下載檔案

你須要Java SDK、 Hibernate包、Ant包、和JDBC Driver。

1、Hibernate包:
http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc

2、Ant包:
http://apache.130th.net/ant/binaries/apache-ant-1.6.1-bin.zip

3、JDBC Driver要依據你用的database來定,一般database官方網站上都會有。Hibernate支援經常使用的database,比方 MySQL, Oracle, PostgreSQL, 和MS-SQL Server。這些資料庫都有JDBC Driver:

Oracle JDBC Driver(下載前必須允許Oracle協議書)
http://otn.oracle.com/software/htdocs/distlic.html?/software/tech/java/sqlj_jdbc/htdocs/jdbc9201.html

MySQL JDBC Driver
http://dev.mysql.com/downloads/connector/j/3.0.html

PostgreSQL JDBC Driver
http://jdbc.postgresql.org/download.html

MS-SQL Server JDBC Driver
http://www.microsoft.com/downloads/details.aspx?FamilyID=9f1874b6-f8e1-4bd6-947c-0fc5bf05bf71&displaylang=en

4、將Hibernate包和Ant包分別解壓至c:/dev/下(此檔案夾不重要,你能夠換其他不論什麼檔案夾)。


配置環境

1、你須要加入?一個新的環境變數: ANT_HOME,讓它指向c:/dev/<你的ANT包所在檔案夾>。並在PATH環境變數裡加入?%ANT_HOME%/bin。

2、你須要加入?一個新的環境變數: JAVA_HOME,讓它指向你的j2sdk根資料夾。並在PATH環境變數裡加入?%JAVA_HOME%/bin。

3、建立一個專案檔夾,比方c:/workspace/My1stHibernate。

在專案檔夾下,另外建立三個檔案夾: src, classes, lib。

在lib檔案夾下,建立兩個檔案夾: hibernate和db。

這樣你有了例如以下的檔案結構:

c:/workspace/My1stHibernate/
c:/workspace/My1stHibernate/src
c:/workspace/My1stHibernate/classes
c:/workspace/My1stHibernate/lib
c:/workspace/My1stHibernate/lib/hibernate
c:/workspace/My1stHibernate/lib/db

4、將c:/dev/<你的Hibernate包所在檔案夾>/hibernate2.jar檔案copy到c:/workspace/My1stHibernate/lib/hibernate下。

將c:/dev/<你的Hibernate包所在檔案夾>/lib/下的全部檔案相同copy到c:/workspace/My1stHibernate/lib/hibernate下。

將你的JDBC Driver檔案(通常是一個jar檔案)copy到c:/workspace/My1stHibernate/lib/db下。


建立資料庫

1、用你最喜愛的database軟體,建立一個hibernate_test的資料庫。

2、在此資料庫下,建立一個table名為CUSTOMER

CREATE TABLE CUSTOMER
(
    CID INTEGER NOT NULL PRIMARY KEY,
    USERNAME VARCHAR(12) NOT NULL,
    PASSWORD VARCHAR(12)
);


編寫Java檔案

public class Customer {
   
    private int id;
    private String username;
    private String password;


    public int getId() {
        return id;
    }

    public String getPassword() {
        return password;
    }

    public String getUsername() {
        return username;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

}

將此類存為c:/workspace/My1stHibernate/src/Customer.java檔案。

編寫Test類

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;

public class Test {

    public static void main(String[] args) {

        try {
            SessionFactory sf =
                new Configuration().configure().buildSessionFactory();
            Session session = sf.openSession();
            Transaction tx = session.beginTransaction();

            for (int i = 0; i < 200; i++) {
                Customer customer = new Customer();
                customer.setUsername("customer" + i);
                customer.setPassword("customer");
                session.save(customer);
            }

            tx.commit();
            session.close();

        } catch (HibernateException e) {
            e.printStackTrace();
        }
    }
}

將此類存為c:/workspace/My1stHibernate/src/Test.java檔案。


建立Hibernate對應檔

由於這裡僅僅有一個Class --- Customer 和一個Table --- CUSTOMER,你僅僅須要建立一個對應檔--- Customer.hbm.xml,來相應Customer類和CUSTOMER表之間的關係。

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>
    <class name="Customer" table="CUSTOMER">
        <id name="id" column="CID">
            <generator class="increment" />
        </id>
        <property name="username" column="USERNAME" />
        <property name="password" column="PASSWORD" />
    </class>
</hibernate-mapping>

把此檔案存為c:/workspace/My1stHibernate/src/Customer.hbm.xml,和Customer.java放在同一檔案夾下。


編寫Ant build.xml檔案


你不一定要知道這個build.xml的細節,事實上Ant也不是Hibernate所必須的。這裡用Ant是為了簡化一些任務,比方: 編譯、copy、執行,等。

<?xml version="1.0" ?>

<project name="My1stHibernate" default="build" basedir=".">

    <property name="base.dir" value="." />
    <property name="src.dir" value="src" />
    <property name="lib.dir" value="lib" />
    <property name="build.dir" value="classes" />

    <path id="myclasspath">
        <fileset dir="${lib.dir}">
            <include name="**/*.jar" />
        </fileset>
        <pathelement location="${build.dir}" />
    </path>

    <target name="init">
        <mkdir dir="${build.dir}" />
    </target>
   
    <target name="build" depends="init" description="compile the source files">
        <javac classpathref="myclasspath" srcdir="${src.dir}" destdir="${build.dir}" />
        <copy todir="${build.dir}" >
            <fileset dir="${src.dir}" >
                <exclude name="**/*.java"/>
            </fileset>
        </copy>
    </target>

    <target name="run" depends="build">
        <java classpathref="myclasspath" classname="Test" fork="true" />
    </target>

    <target name="clean">
        <delete includeEmptyDirs="true">
            <fileset dir="${build.dir}" />
        </delete>
    </target>

</project>


配置Hibernate描寫敘述檔案

Hibernate描寫敘述檔案能夠是一個properties或xml 檔案,當中最重要的是定義資料庫的串連。我這裡列出的是一個XML格式的hibernate.cfg.xml描寫敘述檔案。

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration
    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

<hibernate-configuration>
   
    <session-factory name="java:/hibernate/HibernateFactory">
       
        <property name="show_sql">true</property>
        <property name="connection.driver_class">
            oracle.jdbc.driver.OracleDriver <!-- 這裡是Oracle 9i的JDBC driver class名 -->
        </property>
        <property name="connection.url">
            jdbc:oracle:oci8:@hibernate_test <!-- 這裡是Oracle的hibernate_test資料庫URL -->
        </property>
        <property name="connection.username">
            你的資料庫使用者名稱
        </property>
        <property name="connection.password">
            你的資料庫密碼
        </property>
        <property name="dialect">
            net.sf.hibernate.dialect.Oracle9Dialect <!-- 這裡是Oracle 9i的Dialect -->
        </property>
       
        <mapping resource="Customer.hbm.xml" /> <!-- 指定Customer的對應檔 -->
       
    </session-factory>
   
</hibernate-configuration>

假設你用的不是Oracle 9i,可到C:/dev/<你的Hibernate包所在檔案夾>/src/hibernate.properties檔案中找到你的資料庫,然後替換以上相相應的值。


開始執行

到c:/workspace/My1stHibernate下,執行ant run。假設你嚴格按照以上步驟,應該看到

run:
        [java] log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
        [java] log4j:WARN Please initialize the log4j system properly.
        [java] Hibernate: insert into CUSTOMER (USERNAME, PASSWORD, CID) values (?, ?, ?)
BUILD SUCCESSFUL

到你的hibernate_test資料庫看一下,在CUSTMOR表裡新添了200條記錄,但你沒有寫不論什麼JDBC code。
以後假設你要更換資料庫,僅僅須要改變hibernate.cfg.xml描寫敘述檔案中相應的值就可以。


結論

此文是一篇門檻極低的入門介紹。我給一個全然不懂Hibernate的朋友看,他用了不到30分鐘就執行了他的第一個Hibernate程式,從此引起了 他對Hibernate的興趣。但讀者必須認識到這僅僅是一個開始,此文實乃窺Hibernate冰山一角上的一顆小冰晶。千裡之行始於足下,你能夠把此文 當作邁向Hibernate大道的一個起點。



史上最簡單的Hibernate入門簡單介紹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.