Db2 表:Test 只有一个测试字段:name character(10)
Hibernate的hbm文件:Test.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
<hibernate-mapping>
<class name="Test" table="test">
<composite-id name="testpk" class="Testpk" unsaved-value="any">
<key-property name="name" column="name" type="string"/>
</composite-id>
</class>
</hibernate-mapping>
Test.java
import java.io.Serializable;
public class Test implements Serializable{
private Testpk testpk;
public void setTestpk(Testpk value){
this.testpk=value;
}
public Testpk getTestpk(){
return this.testpk;
}
}
Testpk.java
import java.io.Serializable;
public class Testpk implements Serializable{
private String name;
public String getName()
{
return this.name;
}
public void setName(String value){
this.name=value;
}
public boolean equals(Object other) {
Testpk that = (Testpk) other;
return this.name.equals(that.name);
}
/**
* Returns the hash code for the key.
*/
public int hashCode() {
return (this.name.hashCode());
}
}
测试代码:
Test t=new Test();
Testpk tpk=new Testpk();
tpk.setName("test000000");
t.setTestpk(tpk);
session.save(t);
最后值得注意的是当要load的时候,不能简单的Test t=(Test)session.load(Test.class,"test000000"); 而使用一个Testpk作为一个实体类的标识符。
所以应该这么写:
Testpk tpk=new Testpk();
tpk.setName("test000000");
Test t=(Test)session.load(Test.class,tpk);
环境DB2、Eclipise、Hibernate2测试成功