请问如何在hibernate的hbm文件中配置两个主键? 如果不可以那应该在哪配置,如果可以那如何配置,谢谢。
应该是复合主键配置吧
<hibernate-mapping>
<class name="com.suxiaolei.hibernate.pojos.People" table="people">
<!-- 复合主键使用composite-id标签 -->
<composite-id>
<!-- key-property标签表示哪一些属性对应复合主键 -->
<key-property name="id" column="id" type="string"></key-property>
<key-property name="name" column="name" type="string"></key-property>
</composite-id>
<property name="age" column="age" type="integer"></property>
</class>
</hibernate-mapping>
Hibernate中使用复合主键时需要注意一些规则:
使用复合主键的实体类必须实现Serializable接口。
2. 使用复合主键的实体类必须重写equals和hashCode方法。
/*实体类,使用复合主键必须实现Serializable接口*/
public class People implements Serializable
{
private static final long serialVersionUID = -4888836126783955019L;
private String id;
private String name;
private int age;
public People()
{
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.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;
People other = (People) obj;
if (id == null)
{
if (other.id != null)
return false;
}
else if (!id.equals(other.id))
return false;
if (name == null)
{
if (other.name != null)
return false;
}
else if (!name.equals(other.name))
return false;
return true;
}
}
第一种方式class User{ String name; Stirng addr; int age; ..........}如果name和addr是联合主键,那么配置可以如下:<composite-id> <key-property name="name"/> <key-property name="addr"/></composite-id>第二种方式:class User{ UserKey id; int age; ......}class UserKey{ String name; String addr;}<composite-id class="com......UserKey" name="id"> <key-property name="name"/> <key-property name="addr"/></composite-id>