本文記錄在 JBuilder X 環境下,使用 MS SQL Server 2000 與 JSQL Driver (JDBC 3.0) 建置 Hibernate 2.1.2 開發環境的完整步驟,供參考。
hibernate_full,將 Hibernate lib 目錄下所有 JAR 及 hibernate2.jar 加入。JSQL3,加入 JSQLConnect.jar。testhibernate。Required Libraries 加入上述兩個 Library。Build > Resource 勾選 .xml 檔案為 Copy,確保編譯時映射檔複製到 classes 目錄。src 來源資料夾。hibernate.properties 與 log4j.properties 複製到 src 目錄。註解掉預設的 HypersonicSQL 設定,啟用 MS SQL Server 區塊:
## MS SQL Server
hibernate.dialect net.sf.hibernate.dialect.SQLServerDialect
hibernate.connection.username sa
hibernate.connection.password sa
## JSQL Driver
hibernate.connection.driver_class com.jnetdirect.jsql.JSQLDriver
hibernate.connection.url jdbc:JSQLConnect://yuj/testhi
yuj 為資料庫伺服器機器名,testhi 為資料庫名稱,帳密皆為 sa。
建立標準 JavaBean testhibernate.Person,包含 id、name、address 三個屬性及 getter/setter。
建立映射檔 Person.hbm.xml 放置於同目錄:
<?xml version="1.0" encoding="GB2312"?>
<!DOCTYPE hibernate-mapping SYSTEM "https://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="testhibernate.Person">
<id name="id" unsaved-value="null">
<generator class="uuid.hex"/>
</id>
<property name="name"/>
<property name="address"/>
</class>
</hibernate-mapping>
Client1.java:僅用於初始化建立資料表(僅執行一次)。
Configuration conf = new Configuration().addClass(Person.class);
SchemaExport dbExport = new SchemaExport(conf);
dbExport.setOutputFile("sql.txt");
dbExport.create(true, true);
Client2.java:實際寫入資料。
Configuration conf = new Configuration().addClass(Person.class);
SessionFactory sf = conf.buildSessionFactory();
Session s = sf.openSession();
Transaction t = s.beginTransaction();
Person yuj = new Person();
yuj.setName("john"); yuj.setAddress("上海");
Person x = new Person();
x.setName("zhaoyh"); x.setAddress("上海");
s.save(yuj); s.save(x);
t.commit(); s.close();
執行 Client2 後,資料庫 Person 資料表新增兩筆記錄,代表環境建置成功。