記錄在 JBuilder X (JDK 1.4) 下,使用 JSQL Connect JDBC 3.0 驅動連接 MS SQL Server 2000,整合 Hibernate 2.1.2 的完整配置步驟、映射檔編寫、Schema 自動生成與 CRUD 代碼範例,供同類技術棧開發者參考。
com.jnetdirect.jsql.JSQLDriver (官網註冊下載試用版)hibernate_full:含 hibernate/lib/*.jar + hibernate2.jarJSQL3:JSQLConnect.jartesthibernate,加入上述兩個庫。Project Properties → Build → Resource 勾選 .xml 複製到輸出目錄 (使映射檔隨編譯部署)。src 目錄,複製 hibernate.properties、log4j.properties 至其中。hibernate.properties 針對 SQL Server + JSQL Driver:# 註釋掉預設 HSQLDB 區段
#hibernate.dialect net.sf.hibernate.dialect.HSQLDialect
#hibernate.connection.driver_class org.hsqldb.jdbcDriver
...
# 啟用 SQL Server + JSQL Driver
hibernate.dialect net.sf.hibernate.dialect.SQLServerDialect
hibernate.connection.username sa
hibernate.connection.password sa
hibernate.connection.driver_class com.jnetdirect.jsql.JSQLDriver
hibernate.connection.url jdbc:JSQLConnect://yuj/testhi # yuj=伺服器機器名, testhi=資料庫名
public class Person {
private String id, name, address;
// 標準 getter/setter
}
<?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"/> <!-- UUID 主鍵 -->
</id>
<property name="name"/>
<property name="address"/>
</class>
</hibernate-mapping>
Configuration conf = new Configuration().addClass(Person.class);
SchemaExport dbExport = new SchemaExport(conf);
dbExport.setOutputFile("sql.txt"); // 輸出 DDL 供參考
dbExport.create(true, true); // drop + create
Configuration conf = new Configuration().addClass(Person.class);
SessionFactory sf = conf.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
Person p1 = new Person(); p1.setName("john"); p1.setAddress("上海");
Person p2 = new Person(); p2.setName("zhaoyh"); p2.setAddress("上海");
s.save(p1); s.save(p2); // 持久化
tx.commit();
s.close();
執行 Client1 建表 (查看 sql.txt 確認 DDL),再執行 Client2 插入資料,SQL Server Management Studio 查詢 Person 表確認兩筆記錄。後續可深入探索:HQL 查詢、關聯映射、二級快取、事務邊界聲明、Session 生命週期管理等進階主題。
Microsoft Driver (not recommended!),JSQL 穩定性較好。.hbm.xml 必須隨 Class 輸出 (JBuilder Resource 複製設定),否則 Configuration.addClass() 找不到映射。SchemaExport.create(true, true) 會**刪除重建**表,**僅限初始化/測試**使用,生產環境嚴禁。net.sf.hibernate 包名,3.x+ 遷移為 org.hibernate,遷移時需注意。