在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();