Hibernate复合主键的映射方法

发布于 2011-09-30 | 更新于 2020-09-20

在项目中需要使用到复合主键时,通常是将主键相关的字段封装到一个单独的类中,这个类必须实现:

① 序列化接口 ② 覆盖equals和hashcode方法

例如下面这个例子:

主键类SystemPrivilegePK:

public class SystemPrivilegePK implements Serializable{
private String module;
private String privilege;
public SystemPrivilegePK(){}
public SystemPrivilegePK(String module, String privilege) {
this.module = module;
this.privilege = privilege;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public String getPrivilege() {
return privilege;
}
public void setPrivilege(String privilege) {
this.privilege = privilege;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((module == null) ? 0 : module.hashCode());
result = prime * result
+ ((privilege == null) ? 0 : privilege.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final SystemPrivilegePK other = (SystemPrivilegePK) obj;
if (module == null) {
if (other.module != null)
return false;
} else if (!module.equals(other.module))
return false;
if (privilege == null) {
if (other.privilege != null)
return false;
} else if (!privilege.equals(other.privilege))
return false;
return true;
}

}

系统权限类,使用上面的主键类作为主键:

public class SystemPrivilege {

private SystemPrivilegePK id;
private String name;
private Set<PrivilegeGroup> groups = new HashSet<PrivilegeGroup>();
public Set<PrivilegeGroup> getGroups() {
	return groups;
}
public void setGroups(Set<PrivilegeGroup> groups) {
	this.groups = groups;
}

public SystemPrivilege(){}

public SystemPrivilege(String module, String privilege, String name) {
	this.name = name;
}

public SystemPrivilege(SystemPrivilegePK id) {
	this.id = id;
}

public SystemPrivilegePK getId() { 
	return id;
}
public void setId(SystemPrivilegePK id) {
	this.id = id;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
@Override
public int hashCode() {
	final int prime = 31;
	int result = 1;
	result = prime * result + ((id == null) ? 0 : id.hashCode());
	return result;
}
@Override
public boolean equals(Object obj) {
	if (this == obj)
		return true;
	if (obj == null)
		return false;
	if (getClass() != obj.getClass())
		return false;
	final SystemPrivilege other = (SystemPrivilege) obj;
	if (id == null) {
		if (other.id != null)
			return false;
	} else if (!id.equals(other.id))
		return false;
	return true;
}

}

在SystemPrivilege的映射文件中这样配置主键:




这样就映射好了复合主键。

本文作者: arthinking

本文链接: https://www.itzhai.comhibernate-mapping-a-composite-primary-key.html

版权声明: 版权归作者所有,未经许可不得转载,侵权必究!联系作者请加公众号。

×
IT宅

关注公众号及时获取网站内容更新。

请帅旋喝一杯咖啡

咖啡=电量,给帅旋充杯咖啡,他会满电写代码!

IT宅

关注公众号及时获取网站内容更新。