Hibernate創建和持久化Product
在向大家詳細介紹持久化Product之前,首先讓大家了解下Hibernate創建一個Product,然后全面介紹。
在我們假想的應用程序中,基本的使用模式非常簡單:我們用Hibernate創建一個Product,然后將其持久化(或者換句話說,保存它);我們將搜索并加載一個已經持久化Product,并確保其可以使用;我們將會更新和刪除Product。
Hibernate創建和持久化Product
現在我們終于用到Hibernate了。使用的場景非常簡單:
1. Hibernate創建一個有效的Product。
2. 在應用程序啟動時使用net.sf.Hibernate.cfg.Configuration獲取net.sf.Hibernate.SessionFactory。
3. 通過調用SessionFactory#openSession(),打開net.sf.Hibernate.Session。
4. 保存Product,關閉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. 創建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,關閉Session
- Transaction t = sess.beginTransaction();
- sess.save(p);
- t.commit();
- sess.close();
- }
- }
當然,INFO行指出我們需要一個Hibernate.properties配置文件。在這個文件中,我們配置要使用的數據庫、用戶名和密碼以及其他選項。使用下面提供的這個示例來連接前面提到的Hypersonic數據庫:
- 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
適當地進行修改(例如,可能需要修改Hibernate.connection.url),并保存到classpath中。這很容易,但那個 test/Hibernate/Product.hbm.xml資源是什么呢?它是一個XML文件,定義了Java對象如何被持久化(映射)到一個數據庫。在該文件中,我們定義數據存儲到哪個數據庫表中,哪個字段映射到數據庫表的哪個列,不同的對象如何互相關聯,等等。讓我們來看一下 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>
【編輯推薦】