隨筆-28  評(píng)論-15  文章-81  trackbacks-0
           

          1 。建立數(shù)據(jù)庫(kù)

          Database:mysql
          drop database if exists SAMPLEDB;
          create database hello;
          use hello;

          create table CUSTOMERS (
            ID int not null primary key,
            NAME varchar(15) not null,
            PASSWORD varchar(8) not null
          );

          2
          。在eclipse 中新建工程hbtest

          3
          。在src中新建package hbm

          4
          。新建pojoCustomer

          package hbm;

          public class Customer {
              private int id;
              private String name;
              private String password;
              /**
               * @return Returns the id.
               */
              public int getId() {
                  return id;
              }
              /**
               * @param id
               *            The id to set.
               */
              public void setId(int id) {
                  this.id = id;
              }
              /**
               * @return Returns the name.
               */
              public String getName() {
                  return name;
              }
              /**
               * @param name
               *            The name to set.
               */
              public void setName(String name) {
                  this.name = name;
              }
              /**
               * @return Returns the password.
               */
              public String getPassword() {
                  return password;
              }
              /**
               * @param password
               *            The password to set.
               */
              public void setPassword(String password) {
                  this.password = password;
              }
              //constructor
              public Customer() {
              }

          }


          5
          。使用myeclipse插件建立hibernate.cfg.xml   位于src目錄下
          <?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> 

          <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

          <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
              <property name="connection.url">
          jdbc:mysql://127.0.0.1:3306/hello</property>
              <property name="myeclipse.connection.profile">
          hbmysql</property>

          <property name="connection.username">root</property>
              <property name="connection.password">
          123</property>
              <mapping resource="hbm/Customer.hbm.xml" />

          </session-factory>

          </hibernate-configuration>


          6
          。在hbm package內(nèi)新建Customer.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">

          <!-- Generated by MyEclipse Hibernate Tools.                   -->
          <hibernate-mapping>
          <class name="hbm.Customer" table="CUSTOMERS">
          <id name="id" column="ID" type="int">
          <generator class="increment"/>
          </id>
          <property name="name" column="NAME" type="string" not-null="true"/>
          <property name="password" column="PASSWORD" type="string" not-null="true"/>
          </class>

          </hibernate-mapping>


          7
          。使用hibernate操作數(shù)據(jù)庫(kù)
          package hbm;

          import org.hibernate.*;
          import org.hibernate.cfg.*;
          import java.util.Iterator;
          import java.util.List;

          public class Hbmain {

              public static SessionFactory sessionFactory;//
          數(shù)據(jù)存儲(chǔ)源
              static {
                  try {
                      Configuration config = new Configuration().configure();
                      sessionFactory = config.buildSessionFactory();

                  } catch (Exception e) {
                      e.printStackTrace();
                  }
              }

              /*
               *
          將一個(gè)customer對(duì)象存入database
               * @Customer customer Object
               */
              public void saveCustomer(Customer ct) {
                  Session session = sessionFactory.openSession();
                  Transaction tx = null;
                  try {
                      tx = session.beginTransaction();
                      session.save(ct);
                      tx.commit();
                  } catch (Exception e) {
                      tx.rollback();
                      e.printStackTrace();
                  } finally {
                      session.close();
                  }
              }

              /*
               *
          查找所有的customer object
               */
              public void findAll() {
                  Session session = sessionFactory.openSession();
                  Transaction tx = null;
                  try {
                      tx = session.beginTransaction();
                      List customers = session.createQuery(
                              "from Customer as c order by c.name asc").list();
                      Iterator it = customers.iterator();
                      System.out.println("append:"+customers.size());
                      while(it.hasNext())
                      {
                          Customer c = (Customer)it.next();
                          System.out.println("ID:" + c.getId());
                          System.out.println("Name:" + c.getName());
                          System.out.println("Pass:" + c.getPassword());
                      }
                      tx.commit();
                  } catch (Exception e) {
                      tx.rollback();
                  } finally {
                      session.close();
                  }

              }

              /*
               *
          修改customer Name
               * @name
               */
              public void loadUpdate(int customer_id, String name) {
                  Session session = sessionFactory.openSession();
                  Transaction tx = null;
                  try {
                      tx = session.beginTransaction();
                      Customer c = (Customer) session.load(Customer.class, customer_id);
                      c.setName(name);
                      tx.commit();

                  } catch (Exception e) {
                      if (tx != null) {
                          tx.rollback();
                      }
                      e.printStackTrace();

                  } finally {
                      session.close();
                  }

              }
            
              /*
               *
          測(cè)試以上的方法
               * save() find() update()
               */
             
              public void test()
              {
                  Customer ct = new Customer();
                  //ct.setId(5);
                  ct.setName("buaa");
                  ct.setPassword("5768");
                  this.saveCustomer(ct);
                  this.findAll();
                  this.loadUpdate(ct.getId(),"phop");
              }
             
             
              public static void main(String[] args) {
                  // TODO Auto-generated method stub
                  Hbmain hb = new Hbmain();
                  hb.test();
                  sessionFactory.close();

              }

          }

          初學(xué)hibernate遇到的幾個(gè)問(wèn)題的解決

          參考書是孫衛(wèi)琴的<精通Hibernate>

          hibernate 3 + mysql 5.0

          書上的例子第2章 初始化 hibernate Configuration實(shí)例

          代碼如下:

          Configuration config = new Configuration();

          config.addClass("Customer.class");

          SessionFactory sessionfactory = config.buildSessionFactory();

          配置文件是 hibernate.properties

          運(yùn)行出錯(cuò) :提示為

          org.hibernate.HibernateException: database product name cannot be null

          顯然是配置文件的問(wèn)題

          我用的配置文件是 hibernate.cfg.xml

          修改為以下代碼 成功運(yùn)行

          Configuration config = new Configuration().configure();
          SessionFactory sessionFactory = config.buildSessionFactory();

          原因:使用了xm作為配置文件,而沒(méi)有選擇properties文件,應(yīng)該使用new Configuration().config();

          書上例子第六章一對(duì)多映射

          customer.hbm.xml

          原代碼為

          <hibernate-mapping>
              <class name="demo1.Customer" table="CUSTOMERS">
                  <id name="id" type="long" column="ID">
                      <generator class="increment" />
                  </id>
                  <property name="name" type="string">
                      <column name="NAME" length="15" />
                  </property>
              </class>
          </hibernate-mapping>

          此時(shí)執(zhí)行其Business.java時(shí)

          Customer customer = (Customer) session.load(Customer.class,
                              new Long(customer_id));

          出現(xiàn)如下錯(cuò)誤

          1 Exception in thread "main" java.lang.NullPointerException
          2  at org.hibernate.tuple.AbstractTuplizer.createProxy(AbstractTuplizer.java:249)
          3  at org.hibernate.persister.entity.BasicEntityPersister.createProxy(BasicEntityPersister.java:2831)
          4  at org.hibernate.event.def.DefaultLoadEventListener.createProxyIfNecessary(DefaultLoadEventListener.java:218)
          5  at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:163)
          6  at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:79)
          7  at org.hibernate.impl.SessionImpl.load(SessionImpl.java:603)
          8  at org.hibernate.impl.SessionImpl.load(SessionImpl.java:596)

          修改為

          <hibernate-mapping default-lazy="false">
          <class name="demo1.Customer" table="CUSTOMERS">
                  <id name="id" type="long" column="ID">
                      <generator class="increment" />
                  </id>
                  <property name="name" type="string">
                      <column name="NAME" length="15" />
                  </property>
              </class>
          </hibernate-mapping>

          問(wèn)題解決

          原因在于: Hibernate 3.0 與Hibernate2.1的源代碼是不兼容的
          在Hibernate2.1中,lazy屬性的默認(rèn)值為“false”,而在Hibernate3.0中,lazy屬性的默認(rèn)值為“true”。

          posted on 2007-10-10 20:52 譚明 閱讀(1630) 評(píng)論(0)  編輯  收藏 所屬分類: Hibernate

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 漳平市| 永济市| 潜江市| 兴业县| 德清县| 长葛市| 芦山县| 旺苍县| 丰都县| 兴仁县| 玉山县| 武宁县| 通化市| 财经| 株洲县| 镇赉县| 环江| 四川省| 阳曲县| 汝南县| 海口市| 定兴县| 茂名市| 游戏| 阜阳市| 长宁县| 平泉县| 霍林郭勒市| 凤山市| 金湖县| 九江县| 建阳市| 句容市| 大连市| 凌源市| 同心县| 商洛市| 宁强县| 仪陇县| 大余县| 淳化县|