本文記錄在 MyEclipse 4.1.1 + Eclipse 3.1.1 環境下,使用 Hibernate 3.0 連接 SQL Server 2000 (jtds-1.0.2 驅動) 的完整步驟,適合初次接觸 ORM 框架的開發者快速上手。
prodcast)。goto 並創建表 test_products:CREATE TABLE test_products (
id INT IDENTITY(1,1) PRIMARY KEY,
aotoid CHAR(50),
username CHAR(50),
price INT,
amount INT
);
右鍵專案 → MyEclipse → Add Hibernate Capabilities,向導會自動生成 src/hibernate.cfg.xml,修改數據源屬性:
<property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="connection.url">jdbc:jtds:sqlserver://192.168.1.88:1433;DatabaseName=goto</property>
<property name="connection.username">sa</property>
<property name="connection.password">hcsys</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
Product.java 對應表字段,實現 Serializable;Product.hbm.xml 定義映射關係,主鍵採用 identity 自增策略:
<id name="id" column="id">
<generator class="identity"/>
</id>
<property name="username" column="username" type="string" length="50"/>
<!-- 其他字段略 -->
在 hibernate.cfg.xml 的 <session-factory> 下添加:
<mapping resource="test/hibernate/Product.hbm.xml"/>
注意: 原文誤寫為 hibernate.cfg.xml 自引用,已修正。
public class InsertProduct {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
Product p = new Product();
p.setAotoid("1"); p.setUsername("zhang");
p.setPrice(10); p.setAmount(10);
session.save(p);
tx.commit(); session.close();
}
}
運行後數據庫新增一條記錄,ID 自動生成。
jtds-1.0.2.jar 在 Build Path 中。SQLServerDialect,高版本可用 SQLServer2008Dialect。MappingException:檢查 .hbm.xml 路徑與包名是否一致。