Hibernate初學---註解配置

來源:互聯網
上載者:User

標籤:style   blog   http   java   color   檔案   

ssh架構是每個java程式員的基本功,工作中雖然沒有用到,還是學習一下,做點學習筆記,算是一點積累吧。

廢話不多說,先上手來一個簡單的demo,感受一把。

開發工具:myeclipse 10

資料庫:mysql

建立個簡單的java工程,

第一步,建立一個學生類,代碼如下:

package com.huawei.vo;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entitypublic class Students {    private int sid;        private String sname;    @Id    //設定主鍵    @GeneratedValue(strategy = GenerationType.AUTO)    //主鍵自動成長策略    public int getSid() {        return sid;    }    public void setSid(int sid) {        this.sid = sid;    }    public String getSname() {        return sname;    }    public void setSname(String sname) {        this.sname = sname;    }        }

hibernate的orm技術很出名,可以把java對象直接映射成表,hibernate提供了兩種方式用來描述對象到表的映射關係,

第一種是通過建立映射描述設定檔,名字也要很規範,要起成Students.hbm.xml,這種方式我不喜歡,而且我在想要是領域對象多了,

那不是要搞一堆對應檔啊,果斷放棄之。

第二種就是基於註解的方式,看起來代碼也很優雅,如上面的代碼。也就是說領域對象學生中同時已經包括了對象到表的映射關係。

第二步,在src目錄下建立hibernate的設定檔hibernate.cfg.xml,配置如下:

<?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"><!-- Generated by MyEclipse Hibernate Tools.                   --><hibernate-configuration><session-factory name="mysql">    <property name="connection.driver_class">        com.mysql.jdbc.Driver    </property>    <property name="connection.url">        jdbc:mysql://localhost:3306/hibernate    </property>    <property name="connection.username">root</property>    <property name="connection.password">root</property>    <property name="dialect">        org.hibernate.dialect.MySQL5Dialect    </property>    <!-- 後台列印sql便於調試 -->    <property name="show_sql">true</property>    <property name="hbm2ddl.auto">update</property>    <property name="current_session_context_class">thread</property>    <mapping class="com.huawei.vo.Students" /></session-factory></hibernate-configuration>

一定要在sessionFactory中把映射關係的類通過<mapping>標籤載入進去。這樣就算配置好了。

用getCurrentSession()擷取session的時候一定要把current_session_context_class屬性設定成thread

第三步,寫一個單元測試類吧,代碼如下:

package com.huawei.vo;import junit.framework.TestCase;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.AnnotationConfiguration;public class TestStudents extends TestCase{    private static SessionFactory sessionFactory;        @Override    protected void setUp() throws Exception {        sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();    }    @Override    protected void tearDown() throws Exception {        sessionFactory.close();    }    public void testSave()    {        Session session = sessionFactory.getCurrentSession();        Transaction tx = session.beginTransaction();        try        {            Students s = new Students();            s.setSname("yaoying");            session.save(s);            tx.commit();        }        catch (Exception ex)        {            tx.rollback();        }    }}

這裡session的擷取有兩種方式:

1、通過sessionFactory的openSession()擷取。

2、通過sessionFactory的getCurrentSession()擷取。

由於第二種方式擷取的session是跟當前線程綁定的,也就是說只要是單線程操作每次獲得的是同一個session,而且hibernate在事務的提交和復原後會

自動幫你完成session的關閉操作,如果是openSession每次會獲得一個新的session執行個體,需要手動完成session的關閉。

最後,執行testSave成功後會看到綠色的進度條。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.