Welcome 布拉格

          BlogJava 首頁 聯系 聚合 管理
            6 Posts :: 13 Stories :: 15 Comments :: 0 Trackbacks

          Hibernate初體驗Cat之快速上手

          ?

           Hibernate的手冊里的Cat例子感覺很不明了,很難照著它輕松的運行起第一個例子,費了點周折,總算看到一點結果,如果你是新手,可以參考一下,少走一些彎路。

            1.下載tomcat和Hibernate

            Tomcat 5.0.27 | Tomcat 5.0.28 | Hibernate2.1.6

            2. 安裝

            以tomcat+mysql+hibernate為例

            tomcat的安裝,及mysql的安裝和DBCP的配制參見

            http://blog.csdn.net/ahxu/archive/2004/09/01/91611.aspx,這里就不提了,這里假設tomcat+mysql已經配置并測試可用,這里%WebApp%代表你已配置好的一個web應用的root,著重說一下hibernate的安裝,

            1) 解壓下載的壓縮包,將解壓出來的hibernate2.jar復制到%WebApp%/WEB-INF/lib

            2) 將解壓出來的lib目錄下的

            cglib-full-2.0.2.jar
            commons-collections-2.1.1.jar
            commons-logging-1.0.4.jar
            dom4j-1.4.jar
            ehcache-0.9.jar
            jta.jar
            log4j-1.2.8.jar
            odmg-3.0.jar

            文件同樣復制到%WebApp%/WEB-INF/lib,具體請參見解壓出來的lib目錄下的readme.txt。

            3) 將解壓出來的etc目錄下的
            log4j.properties

            文件復制到%WebApp%/WEB-INF/classes。

            3.編寫相關文件

            1) 按照參考文檔,配置hibernate,將以下代碼保存為hibernate.cfg.xml放在%WebApp%/WEB-INF/classes下


            <?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>

          ?


            <property name="connection.datasource">java:comp/env/jdbc/mysql</property>
            <property name="show_sql">false</property>
            <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>

            <!-- Mapping files -->
            <mapping resource="Cat.hbm.xml"/>

            </session-factory>

            </hibernate-configuration>


            

            NOTE:這里與hibernate文檔里的不一樣,這里指定數據源為mysql數據庫jdbc/mysql,方言dialect為net.sf.hibernate.dialect.MySQLDialect。

            2) 將以下代碼保存為Cat.java,并生成相應的Cat.class,放入%WebApp%/WEB-INF/classes,這里無論你用什么方法生成Cat.class,但最終Cat.class應在%WebApp%/WEB-INF/classes/net/sf/hibernate/examples/quickstart目錄下


            package net.sf.hibernate.examples.quickstart;
            public class Cat {

            private String id;
            private String name;
            private char sex;
            private float weight;

            public Cat() {
            }

            public String getId() {
            return id;
            }

            private void setId(String id) {
            this.id = id;
            }

            public String getName() {
            return name;
            }

            public void setName(String name) {
            this.name = name;
            }

            public char getSex() {
            return sex;
            }

          ?

          ?


            public void setSex(char sex) {
            this.sex = sex;
            }

            public float getWeight() {
            return weight;
            }

            public void setWeight(float weight) {
            this.weight = weight;
            }

            }

          ?

            3) 將以下代碼保存為O/R映射文件Cat.hbm.xml,放入%WebApp%/WEB-INF/classes


            <?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="net.sf.hibernate.examples.quickstart.Cat" table="CAT">
            <!-- A 32 hex character is our surrogate key. It's automatically
            generated by Hibernate with the UUID pattern. -->
            <id name="id" type="string" unsaved-value="null" >
            <column name="CAT_ID" sql-type="char(32)" not-null="true"/>
            <generator class="uuid.hex"/>
            </id>
            <!-- A cat has to have a name, but it shouldn' be too long. -->
            <property name="name">
            <column name="NAME" length="16" not-null="true"/>
            </property>
            <property name="sex"/>
            <property name="weight"/>
            </class>
            </hibernate-mapping


            

            4) 在數據庫內建表,結構如下

            Column |???????? Type????????? | Modifiers
            --------+-----------------------+-----------
            cat_id | character(32)???????? | not null
            name?? | character varying(16) | not null
            sex??? | character(1)????????? |
            weight | real????????????????? |
            Indexes: cat_pkey primary key btree (cat_id)
            

            5) 將以下代碼保存為HibernateUtil.java,并生成相應的HibernateUtil.class,放入%WebApp%/WEB-INF/classes,同樣注意package


            package net.sf.hibernate.examples.quickstart;
            import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;
            import net.sf.hibernate.*;
            import net.sf.hibernate.cfg.*;
            public class HibernateUtil {

            private static Log log = LogFactory.getLog(HibernateUtil.class);

            private static final SessionFactory sessionFactory;

            static {
            try {
            // Create the SessionFactory
            sessionFactory = new Configuration().configure().buildSessionFactory();
            } catch (Throwable ex) {
            log.error("Initial SessionFactory creation failed.", ex);
            throw new ExceptionInInitializerError(ex);
            }
            }

            public static final ThreadLocal session = new ThreadLocal();

            public static Session currentSession() throws HibernateException {
            Session s = (Session) session.get();
            // Open a new Session, if this Thread has none yet
            if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
            }
            return s;
            }

            public static void closeSession() throws HibernateException {
            Session s = (Session) session.get();
            session.set(null);
            if (s != null)
            s.close();
            }
            }

          ?

            NOTE:這里與hibernate文檔也不同,原文檔編繹時缺少2個包,這里已加上。

          6) 將以下代碼保存為test.jsp,放入%WebApp%/,用http測試


            <%@ page language="java" pageEncoding="GB2312" %><%@ page import="net.sf.hibernate.Transaction"%><%@ page import="net.sf.hibernate.Session"%><%@ page import="net.sf.hibernate.cfg.*"%><%@ page import="net.sf.hibernate.Query"%><%@ page import="net.sf.hibernate.examples.quickstart.HibernateUtil"%><%@ page import="net.sf.hibernate.examples.quickstart.Cat"%><%@ page import="java.util.*"%><!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en"><html><head><title>Lomboz JSP</title></head><body bgcolor="#FFFFFF">
            <%
            //添加一只Cat

            Session ses = HibernateUtil.currentSession();
            Transaction tx= ses.beginTransaction();

            Cat princess = new Cat();
            princess.setName("ahxu");
            princess.setSex('F');
            princess.setWeight(7.4f);

            ses.save(princess);
            tx.commit();

            HibernateUtil.closeSession();

            //讀取庫里所有Cat

            ses = HibernateUtil.currentSession();
            tx= ses.beginTransaction();

            Query query = ses.createQuery("select c from Cat as c where c.sex = :sex");
            query.setCharacter("sex", 'F');
            for (Iterator it = query.iterate(); it.hasNext();) {
            Cat cat = (Cat) it.next();
            out.println("Female Cat: " + cat.getName() );
            }

            tx.commit();
            HibernateUtil.closeSession();
            %>
            </body>
            </html>

          ?

            小結

            步驟基本與原文檔步驟相同,只是做了一些補充,方便上手,這里并沒有對其中的一些配置做具體解釋,如有疑問請參見發行包中的相關文檔。

            以上tomcat5.027 + hibernate2.1.6測試通過

          posted on 2007-09-07 18:00 Welcome 閱讀(147) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 淮阳县| 天等县| 四川省| 水富县| 唐海县| 游戏| 嘉定区| 罗山县| 黄山市| 松原市| 咸阳市| 莲花县| 汉中市| 巴东县| 阜新市| 安宁市| 大洼县| 库尔勒市| 商南县| 惠安县| 长寿区| 门源| 宝清县| 石城县| 青神县| 达孜县| 肥西县| 日照市| 都昌县| 丹江口市| 通城县| 武宁县| 铜鼓县| 和林格尔县| 沙田区| 普宁市| 舒城县| 兴安盟| 芦山县| 临清市| 新平|