在Hibernate中关于对复合主键的映射和处理

在Hibernate中关于对复合主键的映射和处理:



例子:

<class name="User" table="USER">
<composite-id name="userId" class="UserId">
<key-property name="userName"
column="USERNAME"/>
<key-property name="organizationId"
column="ORGANIZATION_ID"/>
</composite-id>
<version name="version"
column="VERSION"
unsaved-value="0"/>
<many-to-one name="organization"
class="Organization"
column="ORGANIZATION_ID"
insert="false" update="false"/>
...
</class>
public class UserId extends Serializable {
private String username;
private String organizationId;
public UserId(String username, String organizationId) {
this.username = username;
this.organizationId = organizationId;
}
// Getters...
public boolean equals(Object o) {
if (this == o) return true;
if (o = null) return false;
if (!(o instanceof UserId)) return false;----一般的判断开头都基本这样写

final UserId userId = (UserId) o;
if (!organizationId.equals(userId.getOrganizationId()))
return false;
if (!username.equals(userId.getUsername()))
return false;
return true;
}
public int hashCode() {
return username.hashCode();
)
}
使用如下:

UserId id = new UserId("john", 42);
User user = new User();
// Assign a primary key value
user.setUserId(id);
// Set property values
user.setFirstname("John");
user.setLastname("Doe");
session.saveOrUpdate(user); // will save, since version is 0
session.flush();

posted on 2007-10-06 11:37 刘铮 阅读(358) 评论(0)  编辑  收藏 所属分类: Hibernate


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年11月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

导航

统计

留言簿(1)

文章分类(141)

文章档案(147)

搜索

最新评论