<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    一個(gè)用myeclipse開發(fā)hibernate的入門例子

    Posted on 2007-04-19 15:45 flustar 閱讀(5425) 評論(2)  編輯  收藏 所屬分類: Hibernate



     一、環(huán)境

    1.eclipse 3.2.2
    2.myeclipse 5.1.1
    3.jdk 1.5

    二、簡要說明

    數(shù)據(jù)庫為mysql

     在mysql中建立一個(gè)test數(shù)據(jù)庫,建立cat表
    CREATE TABLE `cat` (
      `cat_id` varchar(32) NOT NULL,
      `name` varchar(16) NOT NULL,
      `sex` varchar(1) default NULL,
      `weight` float(9,3) default NULL,
      PRIMARY KEY  (`cat_id`)
    )

    三、步驟

    1.導(dǎo)入包的準(zhǔn)備工作

    a.新建java project.建立包example
    在它下面編寫類Cat.java

    package example;

     public class Cat  implements java.io.Serializable {


        // Fields   

         private String catId;
         private String name;
         private String sex;
         private Float weight;


        // Constructors

        /** default constructor */
        public Cat() {
        }

     /** minimal constructor */
        public Cat(String name) {
            this.name = name;
        }
       
        /** full constructor */
        public Cat(String name, String sex, Float weight) {
            this.name = name;
            this.sex = sex;
            this.weight = weight;
        }

      
        // Property accessors

        public String getCatId() {
            return this.catId;
        }
       
        public void setCatId(String catId) {
            this.catId = catId;
        }

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

        public String getSex() {
            return this.sex;
        }
       
        public void setSex(String sex) {
            this.sex = sex;
        }

        public Float getWeight() {
            return this.weight;
        }
       
        public void setWeight(Float weight) {
            this.weight = weight;
        } 
    }

    同樣在此包下面編寫Cat.hbm.xml

      <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "<!--
        Mapping file autogenerated by MyEclipse - Hibernate Tools
    -->
    <hibernate-mapping>
        <class name="example.Cat" table="cat" catalog="testhibernate">
            <id name="catId" type="java.lang.String">
                <column name="cat_id" length="32" />
                <generator class="uuid.hex"></generator>
            </id>
            <property name="name" type="java.lang.String">
                <column name="name" length="16" not-null="true" />
            </property>
            <property name="sex" type="java.lang.String">
                <column name="sex" length="1" />
            </property>
            <property name="weight" type="java.lang.Float">
                <column name="weight" precision="9" scale="3" />
            </property>
        </class>
    </hibernate-mapping>

    b.在工程的src里面加入一個(gè)包,用來存放將要生成的HibernateSessionFactory。包名如(example.util)。
    導(dǎo)入hibernate(生成的代碼:
    package example.util;

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

    /**
     * Configures and provides access to Hibernate sessions, tied to the
     * current thread of execution.  Follows the Thread Local Session
     * pattern, see
    {@link http://hibernate.org/42.html }.
     */
    public class HibernateSessionFactory {

        /**
         * Location of hibernate.cfg.xml file.
         * Location should be on the classpath as Hibernate uses 
         * #resourceAsStream style lookup for its configuration file.
         * The default classpath location of the hibernate config file is
         * in the default package. Use #setConfigFile() to update
         * the location of the configuration file for the current session.  
         */
        private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
     private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
        private  static Configuration configuration = new Configuration();
        private static org.hibernate.SessionFactory sessionFactory;
        private static String configFile = CONFIG_FILE_LOCATION;

        private HibernateSessionFactory() {
        }
     
     /**
         * Returns the ThreadLocal Session instance.  Lazy initialize
         * the <code>SessionFactory</code> if needed.
         *
         *  @return Session
         *  @throws HibernateException
         */
        public static Session getSession() throws HibernateException {
            Session session = (Session) threadLocal.get();

      if (session == null || !session.isOpen()) {
       if (sessionFactory == null) {
        rebuildSessionFactory();
       }
       session = (sessionFactory != null) ? sessionFactory.openSession()
         : null;
       threadLocal.set(session);
      }

            return session;
        }

     /**
         *  Rebuild hibernate session factory
         *
         */
     public static void rebuildSessionFactory() {
      try {
       configuration.configure(configFile);
       sessionFactory = configuration.buildSessionFactory();
      } catch (Exception e) {
       System.err
         .println("%%%% Error Creating SessionFactory %%%%");
       e.printStackTrace();
      }
     }

     /**
         *  Close the single hibernate session instance.
         *
         *  @throws HibernateException
         */
        public static void closeSession() throws HibernateException {
            Session session = (Session) threadLocal.get();
            threadLocal.set(null);

            if (session != null) {
                session.close();
            }
        }

     /**
         *  return session factory
         *
         */
     public static org.hibernate.SessionFactory getSessionFactory() {
      return sessionFactory;
     }

     /**
         *  return session factory
         *
         * session factory will be rebuilded in the next call
         */
     public static void setConfigFile(String configFile) {
      HibernateSessionFactory.configFile = configFile;
      sessionFactory = null;
     }

     /**
         *  return hibernate configuration
         *
         */
     public static Configuration getConfiguration() {
      return configuration;
     }

    }

    對工程名點(diǎn)鼠標(biāo)右鍵。選擇myeclipse->add

    hibernate capabicities。

    在彈出的窗口選擇中Hibernate 3.0 Core Libraries和Hibernate 3.0 Advanced Support Libraries

    下面選中Copy checked Library Jars to project folder and add to build-path。點(diǎn)擊下一步。

    c.默認(rèn)(hibernate cofig file),下一步。

    d.選中User JDBC driver
    connect url:  jdbc:mysql://localhost:3306/test
    Driver class:  org.gjt.mm.mysql.Driver
    username:  root
    password: ******
    Dialect: mysql

    e.在第一行包選擇里面,選擇在前面第二大步建的包如(example)。點(diǎn)擊完成。

    f.彈出的畫面中 選擇properties的add按鈕。在Property中加入show_sql,Value中加入true。點(diǎn)確定

    保存設(shè)置。在mappings中點(diǎn)add加入前面建立的Cat.hbm.xml。最后生成的hibernate.cfg.xml文件如下
    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
              "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
              "

    <!-- Generated by MyEclipse Hibernate Tools.                   -->
    <hibernate-configuration>

    <session-factory>
     <property name="connection.username">root</property>
     <property name="connection.url">
      jdbc:mysql://localhost:3306/testhibernate
     </property>
     <property name="dialect">
      org.hibernate.dialect.MySQLDialect
     </property>
     <property name="connection.password">123456</property>
     <property name="connection.driver_class">
      org.gjt.mm.mysql.Driver
     </property>
     <property name="show_sql">true</property>
     <mapping resource="example/Cat.hbm.xml" />

    </session-factory>

    </hibernate-configuration>


    3.測試 新建包test 在其中建立測試文件TestHibernate.java
    package test;

    import java.util.Iterator;
    import java.util.List;
    import example.*;
    import example.util.*;
    import org.hibernate.Session;
    import org.hibernate.Transaction;

    public class TestHibernate {
     Session session=null;
     Transaction tx=null;
    public static void main(String[] args) {
     TestHibernate th=new TestHibernate(); 
     List cl=th.getAllCats();
     if(cl!=null){
      Iterator it=cl.iterator();
      while(it.hasNext()){
       Cat cat=(Cat)it.next();
       System.out.println("catID:"+cat.getCatId()+"name:"+cat.getName()+"sex:"+cat.getSex());
      }
     }
      
      

     }
    public List getAllCats(){
     session=HibernateSessionFactory.getSession();
     List catlist=null;
     try{
      tx=session.beginTransaction();
      catlist=session.createQuery("from Cat").list();
      return catlist;
     }catch(Exception ex){
      System.err.println(ex.getMessage());
      return null;
     }finally{
      HibernateSessionFactory.closeSession();
     }
    }

    }

     

     

    Feedback

    # re: 一個(gè)用myeclipse開發(fā)hibernate的入門例子  回復(fù)  更多評論   

    2007-04-30 12:54 by qinyi
    收藏

    # re: 一個(gè)用myeclipse開發(fā)hibernate的入門例子  回復(fù)  更多評論   

    2007-08-13 18:52 by bai
    很好
    3X

    posts - 146, comments - 143, trackbacks - 0, articles - 0

    Copyright © flustar

    主站蜘蛛池模板: 亚洲精品美女在线观看| 久久久久久久久亚洲| 亚洲videosbestsex日本| 亚欧在线精品免费观看一区| 日韩精品一区二区亚洲AV观看| 无码少妇一区二区浪潮免费| 亚洲第一精品电影网| 青柠影视在线观看免费高清| 人人狠狠综合久久亚洲婷婷| 久久精品国产免费| 亚洲色偷偷av男人的天堂| 成年在线观看网站免费| 亚洲精品国产第一综合99久久| 中文成人久久久久影院免费观看| 永久看日本大片免费35分钟| 亚洲AV无码成人精品区蜜桃 | 亚洲人成电影亚洲人成9999网| 亚洲欧洲日产国码二区首页| 久久综合国产乱子伦精品免费| 又粗又硬免费毛片| 在线播放国产不卡免费视频| 亚洲精品乱码久久久久久久久久久久 | 中文字幕在线免费观看视频| 亚洲成av人影院| 亚洲一区二区三区免费在线观看| 久久精品国产精品亚洲人人| 中文字幕无码一区二区免费| 亚洲一区免费在线观看| 在线免费观看国产视频| 在线免费播放一级毛片 | a级毛片毛片免费观看久潮喷| 四虎免费在线观看| 免费一区二区无码视频在线播放| 综合在线免费视频| 国产成人不卡亚洲精品91| 精品亚洲综合久久中文字幕| 免费黄色网址网站| 猫咪免费人成在线网站| 久久精品视频亚洲| 国产精品极品美女免费观看| 黄色网站软件app在线观看免费|