Hibernate創(chuàng)建和持久化Product
在向大家詳細(xì)介紹持久化Product之前,首先讓大家了解下Hibernate創(chuàng)建一個Product,然后全面介紹。
在我們假想的應(yīng)用程序中,基本的使用模式非常簡單:我們用Hibernate創(chuàng)建一個Product,然后將其持久化(或者換句話說,保存它);我們將搜索并加載一個已經(jīng)持久化Product,并確保其可以使用;我們將會更新和刪除Product。
Hibernate創(chuàng)建和持久化Product
現(xiàn)在我們終于用到Hibernate了。使用的場景非常簡單:
1. Hibernate創(chuàng)建一個有效的Product。
2. 在應(yīng)用程序啟動時使用net.sf.Hibernate.cfg.Configuration獲取net.sf.Hibernate.SessionFactory。
3. 通過調(diào)用SessionFactory#openSession(),打開net.sf.Hibernate.Session。
4. 保存Product,關(guān)閉Session。
正如我們所看到的,這里沒有提到JDBC、SQL或任何類似的東西。非常令人振奮!下面的示例遵循了上面提到的步驟:
- package test;
- import net.sf.hibernate.Session;
- import net.sf.hibernate.SessionFactory;
- import net.sf.hibernate.Transaction;
- import net.sf.hibernate.cfg.Configuration;
- import test.hibernate.Product;
- // 用法:
- // java test.InsertProduct name amount price
- public class InsertProduct {
- public static void main(String[] args)
- throws Exception {
- // 1. 創(chuàng)建Product對象
- Product p = new Product();
- p.setName(args[0]);
- p.setAmount(Integer.parseInt(args[1]));
- p.setPrice(Double.parseDouble(args[2]));
- // 2. 啟動Hibernate
- Configuration cfg = new Configuration()
- .addClass(Product.class);
- SessionFactory sf = cfg.buildSessionFactory();
- // 3. 打開Session
- Session sess = sf.openSession();
- // 4. 保存Product,關(guān)閉Session
- Transaction t = sess.beginTransaction();
- sess.save(p);
- t.commit();
- sess.close();
- }
- }
當(dāng)然,INFO行指出我們需要一個Hibernate.properties配置文件。在這個文件中,我們配置要使用的數(shù)據(jù)庫、用戶名和密碼以及其他選項。使用下面提供的這個示例來連接前面提到的Hypersonic數(shù)據(jù)庫:
- hibernate.connection.username=sa
- hibernatehibernate.connection.password=
- hibernate.connection.url=jdbc:hsqldb:/home/davor/hibernate/orders
- hibernate.connection.driver_class=org.hsqldb.jdbcDriver
- hibernate.dialect=net.sf.hibernate.dialect.HSQLDialect
適當(dāng)?shù)剡M(jìn)行修改(例如,可能需要修改Hibernate.connection.url),并保存到classpath中。這很容易,但那個 test/Hibernate/Product.hbm.xml資源是什么呢?它是一個XML文件,定義了Java對象如何被持久化(映射)到一個數(shù)據(jù)庫。在該文件中,我們定義數(shù)據(jù)存儲到哪個數(shù)據(jù)庫表中,哪個字段映射到數(shù)據(jù)庫表的哪個列,不同的對象如何互相關(guān)聯(lián),等等。讓我們來看一下 Product.hbm.xml。
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE hibernate-mappingPUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">- <hibernate-mapping>
- <class name="test.hibernate.Product"table="products">
- <id name="id" type="string"unsaved-value="null">
- <column name="id" sql-type="char(32)"not-null="true"/>
- <generator class="uuid.hex"/>
- </id>
- <property name="name">
- <column name="name" sql-type="char(255)"not-null="true"/>
- </property>
- <property name="price">
- <column name="price" sql-type="double"not-null="true"/>
- </property>
- <property name="amount">
- <column name="amount" sql-type="integer"not-null="true"/>
- </property>
- </class>
- </hibernate-mapping>
【編輯推薦】