一個簡單的hibernate執行個體(之一)

來源:互聯網
上載者:User
一、下載hibernate-3.2 core版本,解壓。
二、開啟eclipse,建立一個使用者庫,命名為:hibernate3.2,匯入剛解壓的hibernate目錄下的hibernate3.jar
並/lib目錄下的所有jar檔案。在Builder path的source and output fold中選擇Folder,並預設給出的檔案夾名。
在as JRE library use中選擇JRE_LIB variable。
三、建立一個java工程。在其屬性的Java Build Path中引入剛建立的hibernate3.2使用者庫並mysql的java驅動(
視你所用的資料庫而定,在這我用的是mysql資料庫)。
四、在src中建立一個包,設為px.malijun,並在其中建立以下幾個Java Class:


User.java   package px.malijun;      public class User {       private int id;       private String name;       private String password;       private String email;       public String getEmail() {           return email;       }       public void setEmail(String email) {           this.email = email;       }       public String getName() {           return name;       }       public void setName(String name) {           this.name = name;       }       public String getPassword() {           return password;       }       public void setPassword(String password) {           this.password = password;       }       public int getId() {           return id;       }       public void setId(int id) {           this.id = id;       }     }  

建立相應的xml對應檔:

User.hbm.xml
  <?xml version="1.0" encoding='utf-8'?>   <!DOCTYPE hibernate-mapping PUBLIC           "-//Hibernate/Hibernate Mapping DTD 3.0//EN"           "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">      <hibernate-mapping>       <class name="px.malijun.User" table="users">       <id name="id">        <generator class="identity"/>        </id>           <property name="name"/>           <property name="password"/>           <property name="email"/>       </class>   </hibernate-mapping>  

在資料庫中建立一個myproject(按你的意思定名)資料庫,在其中建立一個users表(向RoR學習):
  CREATE TABLE `users` (     `id` int(11) NOT NULL auto_increment,     `name` varchar(255) default NULL,     `password` varchar(255) default NULL,     `email` varchar(255) default NULL,     PRIMARY KEY  (`id`)   ) 


註:我是用phpmyadmin對mysql資料庫進行管理的,在建立的時候我特意為其選擇了utf-8編碼。


在src的根目錄下(以上的user.hbm.xml對應檔與User.java在同一目錄下)建立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">      <hibernate-configuration>          <session-factory>                  <!-- 顯示實際操作資料庫時的SQL -->                      <property name="show_sql">true</property>                      <!-- SQL 方言,這邊設定的是MySQL -->                      <property name="dialect">org.hibernate.dialect.MySQLDialect</property>                      <!-- JDBC 驅動程式 -->                      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>                      <!-- JDBC URL 注意這邊我設定的所使用的編碼 -->                      <property name="connection.url">jdbc:mysql://localhost:3306/myproject?useUnicode=true&amp;characterEncoding=utf8</property>                      <!-- 資料庫使用者 -->                      <property name="connection.username">root</property>                      <!-- 資料庫密碼 -->                      <property name="connection.password"></property>                      <!-- 以下設定對象與資料庫表格映像檔案 -->           <mapping resource="px/malijun/User.hbm.xml"/>              </session-factory>      </hibernate-configuration>   

ok 了,下面我們就進入我們的實際使用階段了:


由於常規操作都類似,我們建立了一個抽象類別:

HibernateBase.java
  package px.malijun;      import org.hibernate.*;   import org.hibernate.cfg.*;   import java.util.*;   import java.io.IOException;   import java.io.PrintWriter;                public abstract class HibernateBase         {        protected SessionFactory sessionFactory;//會話工廠,用於建立會話        protected Session session;//hibernate會話        protected Transaction transaction; //hiberante事務                public HibernateBase()throws HibernateException        {        this.initHibernate();        }        // 協助方法        protected void initHibernate()        throws HibernateException {                // 裝載配置,構造SessionFactory對象        sessionFactory = new Configuration().configure().buildSessionFactory();        }                /**       *開始一個hibernate事務       */        protected void beginTransaction()        throws HibernateException {                session = sessionFactory.openSession();        transaction = session.beginTransaction();        }                /**       *結束一個hibernate事務。       */        protected void endTransaction(boolean commit)        throws HibernateException {                if (commit) {        transaction.commit();        } else {        //如果是唯讀操作,不需要commit這個事務。        transaction.rollback();        }        session.close();        }   }  

然後建立一個具體針對User操作的一個類:
UserBean.java
  package px.malijun;      import org.hibernate.*;   import org.hibernate.cfg.*;   import java.util.*;      /**   * 和course相關的商務邏輯   */   public class UserBean extends HibernateBase {       public UserBean() throws HibernateException {           super();       }          /**       * 增加一個Course       */       public void addUser(User user) throws HibernateException {           beginTransaction();           session.save(user);           endTransaction(true);       }          /**       * 查詢系統中所有的Course,返回的是包含有Course持久對象的Iterator。       */       public Iterator getAllUsers() throws HibernateException {           String queryString = "select users from User as user";           beginTransaction();           Query query = session.createQuery(queryString);           Iterator it = query.iterate();           return it;       }          /**       * 刪除給定ID的course       */       public void deleteUser(String id) throws HibernateException {           beginTransaction();           User user = (User) session.load(User.class, id);           session.delete(user);           endTransaction(true);       }          /**       * 按course的名字進行模糊尋找,返回的是包含有Course持久對象的Iterator。       */       public

聯繫我們

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