maven配置hibernate

來源:互聯網
上載者:User

標籤:maven   hibernate   myeclipse   

本文為原創,轉載請註明 來至: http://blog.csdn.net/j903829182/article/details/38147659

1.進入cmd建立一個web項目並匯入myeclipse中修改好目錄結構和配置好項目的屬性,詳細的我這裡就不說了,具體請參照我的部落格:http://blog.csdn.net/j903829182/article/details/38128777裡面有具體的建立配置的方法和步驟,這這裡我主要講解下怎麼使用maven來組態管理hibernate

我這裡主要參考的是hibernate3.6.10裡面的官方,文檔,我也是主要按照官方文檔寫得這個小例子。看文檔可以提高自己的學習能力,和閱讀理解能力,可以多看看官方的文檔,因為他是最權威的。

2.要使用maven管理hibernate首先就應該匯入hibernate的配置依賴包,所以我們先寫pom.xml檔案。

<span style="font-size:18px;"><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>com.wj.hibernate</groupId>  <artifactId>maven3</artifactId>  <packaging>war</packaging>  <version>1.0-SNAPSHOT</version>  <name>maven3 Maven Webapp</name>  <url>http://maven.apache.org</url>      <!-- 屬性配置 -->    <properties>   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  </properties>  <dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>3.8.1</version>      <scope>test</scope>    </dependency>         <!-- 添加Hibernate依賴 -->      <dependency>      <groupId>org.hibernate</groupId>      <artifactId>hibernate-core</artifactId>      <version>3.6.10.Final</version>    </dependency>        <!-- 添加Log4J依賴 -->      <dependency>      <groupId>log4j</groupId>      <artifactId>log4j</artifactId>      <version>1.2.16</version>    </dependency>        <dependency>       <groupId>org.slf4j</groupId>       <artifactId>slf4j-nop</artifactId>       <version>1.6.4</version>    </dependency>        <!-- 添加javassist -->      <dependency>       <groupId>javassist</groupId>       <artifactId>javassist</artifactId>        <version>3.12.0.GA</version>     </dependency>        <!-- mysql資料庫的驅動包 -->    <dependency>        <groupId>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>        <version>5.1.6</version>    </dependency>              </dependencies>  <build>    <finalName>maven3</finalName>  </build></project></span>



在這裡先看hibernate的配置需要的包,資料庫的包配置,你先忽略,我接下來會講解。


3.接下來我們建立一個類,用來代表那些我們希望儲存在資料庫裡的 event,這是一個具有一些屬性的簡單 JavaBean 類:

<span style="font-size:18px;">package org.hibernate.tutorial.domain;import java.util.Date;public class Event {private Long id;//id    private String title;//標題    private Date date;//日期public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public Date getDate() {return date;}public void setDate(Date date) {this.date = date;}    }</span>

把這個檔案儲存到 src/main/java/org/hibernate/tutorial/domain 目錄下。


4.配置hibernate的對應檔,Hibernate 需要知道怎樣去載入(load)和儲存(store)持久化類的對象。這正是 Hibernate 對應檔發揮作用的地方。對應檔告訴 Hibernate 它應該訪問資料庫(database)裡面的哪個表(table)及應該使用表裡面的哪些欄位(column)。 

<span style="font-size:18px;"><?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="org.hibernate.tutorial.domain">    <class name="Event" table="EVENTS">        <id name="id" column="EVENT_ID">            <generator class="native"/>        </id>        <property name="date" type="timestamp" column="EVENT_DATE"/>        <property name="title"/>    </class></hibernate-mapping></span>
把這個對應檔儲存為 src/main/resources/org/hibernate/tutorial/domain/Event.hbm.xml。 


5.Hibernate 配置.你應該有了持久化類和它的對應檔。現在是配置 Hibernate 的時候了

建立檔案hibernate.cfg.xml並把這個檔案儲存為src/main/resources 目錄下。注意maven的資源檔根據預定都放在src/main/resources 目錄下。

hibernate.cfg.xml裡面的代碼:

<span style="font-size:18px;"><?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">org.gjt.mm.mysql.Driver</property>        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>        <property name="connection.username">root</property>        <property name="connection.password">root</property>        <!-- JDBC connection pool (use the built-in) -->        <property name="connection.pool_size">1</property>        <!-- SQL dialect -->        <property name="dialect">org.hibernate.dialect.MySQLDialect</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>        <!-- Echo all executed SQL to stdout -->        <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="org/hibernate/tutorial/domain/Event.hbm.xml"/>    </session-factory></hibernate-configuration></span>



6.添加mysql資料庫的驅動包。由於mysql資料驅動包,不是maven的是我本地的所以我要是引用的話,需要依據的一定的規則,把資料庫的驅動包放到指定的目錄下面,最後在pom.xml檔案裡面配置如下

<span style="font-size:18px;"><!-- mysql資料庫的驅動包 -->    <dependency>        <groupId>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>        <version>5.1.6</version>    </dependency></span>

對於maven管理本地的包和maven管理各種資料庫,詳細的可以參考

http://blog.163.com/[email protected]/blog/static/119907206201210223827126/


7.編譯測試一下,我們的項目是否有問題

我們將用 Maven 構建這個教程。你將需要安裝 Maven;你可以從Maven 下載頁面獲得 Maven。Maen 將讀取我們先前建立的/pom.xml 並知道執行基本的專案工作。首先,讓我們運行 compile 目標來確保我們可以編譯到目前為止的所有程式: 

使用CMD視窗,進入當前項目的根目錄:

第一條命令:輸入mvn compile



注意:這裡一定要成功啊,即   BUILD SUCCESS

第二條命令:輸入mvn test-compile



同樣的,這裡一定要 BUILD SUCCESS


8啟動和輔助類

是時候來載入和儲存一些Event 對象了,但首先我們得編寫一些基礎的代碼以完成設定。我們必須啟動 Hibernate,此過程包括建立一個全域的SessoinFactory,並把它儲存在應用程式代碼容易訪問的地方。SessionFactory 可以建立並開啟新的Session。一個 Session 代表一個單線程的單元操作,org.hibernate.SessionFactory 則是個安全執行緒的全域對象,只需要被執行個體化一次。 

我們將建立一個HibernateUtil 輔助類(helper class)來負責啟動 Hibernate 和更方便地操作org.hibernate.SessionFactory。讓我們來看一下它的實現: 

package org.hibernate.tutorial.util;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil {//定義靜態SessionFactory,產生單例,只產生一個SessionFactoryprivate static final SessionFactory sessionFactory = buildSessionFactory();//用來初始化SessionFactory    private static SessionFactory buildSessionFactory() {        try {            // Create the SessionFactory from hibernate.cfg.xml            return new Configuration().configure().buildSessionFactory();        }        catch (Throwable ex) {            // Make sure you log the exception, as it might be swallowed            System.err.println("Initial SessionFactory creation failed." + ex);            throw new ExceptionInInitializerError(ex);        }    }    //得到SessionFactory    public static SessionFactory getSessionFactory() {        return sessionFactory;//返回SessionFactory的對象    }}


把這段代碼儲存為src/main/java/org/hibernate/tutorial/util/HibernateUtil.java

這個類不但在它的靜態初始化過程(僅當載入這個類的時候被 JVM 執行一次)中產生全域的org.hibernate.SessionFactory,而且隱藏了它使用了靜態 singleton 的事實。它也可能在應用程式伺服器中的 JNDI 尋找org.hibernate.SessionFactory。 

再次編譯這個應用程式應該不會有問題。最後我們需要配置一個日誌(logging)系統 — Hibernate 使用通用日誌介面,允許你在 Log4j 和 JDK 1.4 日誌之間進行選擇。多數開發人員更喜歡 Log4j:從 Hibernate 的發布包中(它在etc/ 目錄下)拷貝log4j.properties 到你的src 目錄,與hibernate.cfg.xml 放在一起。看一下配置樣本,如果你希望看到更加詳細的輸出資訊,你可以修改配置。預設情況下,只有 Hibernate 的啟動資訊才會顯示在標準輸出上。

樣本的基本架構完成了 — 現在我們可以用 Hibernate 來做些真正的工作。  


9載入並儲存物件

package org.hibernate.tutorial;import java.util.Date;import org.hibernate.Session;import org.hibernate.tutorial.domain.Event;import org.hibernate.tutorial.util.HibernateUtil;public class EventManager {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubEventManager mgr = new EventManager();        //if (args[0].equals("store")) {          mgr.createAndStoreEvent("My Event4", new Date());//調用函數插入資料        //}        HibernateUtil.getSessionFactory().close();}private void createAndStoreEvent(String title, Date theDate) {//得到目前啟動並執行session        Session session = HibernateUtil.getSessionFactory().getCurrentSession();        session.beginTransaction();//開始事務        Event theEvent = new Event();//建立bean對象        theEvent.setTitle(title);//設定標題        theEvent.setDate(theDate);//設定日期        session.save(theEvent);//儲存對象        session.getTransaction().commit();//提交事務    }}

10.項目結構








11.由於我在hibernate.cfg.xml中採用了<property name="hbm2ddl.auto">update</property>這句話,所以,可以不用手動建立表,自動會給我建立。

12.直接右擊EventManager這個類,選擇run as ---〉java Application運行,看console有sql語言列印出來,你在到資料庫裡面看看錶,裡面已經插入了資料了。

13.總結,至此maven配置hibernate已經全部,講解完了,至於日誌我匯入了,但是沒用,把log4j.properties的字碼頁貼出來:

### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file hibernate.log ####log4j.appender.file=org.apache.log4j.FileAppender#log4j.appender.file.File=hibernate.log#log4j.appender.file.layout=org.apache.log4j.PatternLayout#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change 'info' to 'debug' ###log4j.rootLogger=warn, stdout#log4j.logger.org.hibernate=infolog4j.logger.org.hibernate=debug### log HQL query parser activity#log4j.logger.org.hibernate.hql.ast.AST=debug### log just the SQL#log4j.logger.org.hibernate.SQL=debug### log JDBC bind parameters ###log4j.logger.org.hibernate.type=info#log4j.logger.org.hibernate.type=debug### log schema export/update ###log4j.logger.org.hibernate.tool.hbm2ddl=debug### log HQL parse trees#log4j.logger.org.hibernate.hql=debug### log cache activity ####log4j.logger.org.hibernate.cache=debug### log transaction activity#log4j.logger.org.hibernate.transaction=debug### log JDBC resource acquisition#log4j.logger.org.hibernate.jdbc=debug### enable the following line if you want to track down connection ###### leakages when using DriverManagerConnectionProvider ####log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace

log4j.properties是放在src/main/resources/目錄下面的


後台插入資料是列印的資料資訊:

Hibernate: 
    insert 
    into
        EVENTS
        (EVENT_DATE, title) 
    values
        (?, ?)













































maven配置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.