0

嗨,我想在我的数据库中为我的 person 表设置一个唯一的姓氏和名字。我的人的休眠 xml 映射是

package com.me.POJO;

public class Person {

private int personId;
private String firstName;
private String lastName;
private String streetAddress;
private String aptNo;
private String city;
private int zipCode;

public Person(){}
public Person(String firstName, String lastName, String streetAddress,
String aptNo, String city, int zipCode) {
this.firstName = firstName;
this.lastName = lastName;
this.streetAddress = streetAddress;
this.aptNo = aptNo;
this.city = city;
this.zipCode = zipCode;
}

public int getPersonId() {
return personId;
}

public void setPersonId(int personId) {
this.personId = personId;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getStreetAddress() {
return streetAddress;
}

public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}

public String getAptNo() {
return aptNo;
}

public void setAptNo(String aptNo) {
this.aptNo = aptNo;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public int getZipCode() {
return zipCode;
}

public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}

}

我的人的休眠 hbm.xml 文件是:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Apr 9, 2012 2:49:54 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.me.POJO.Person" table="Person">
<id name="personId" type="int">
<column name="personId_PK" />
<generator class="native"></generator>
</id>
<property name="aptNo" type="java.lang.String">
<column name="aptNo" />
</property>
<property name="city" type="java.lang.String">
<column name="city" />
</property>
<property name="firstName" type="java.lang.String">
<column name="firstName" />
</property>
<property name="lastName" type="java.lang.String">
<column name="lastName" />
</property>
<property name="streetAddress" type="java.lang.String">
<column name="streetAddress" />
</property>
<property name="zipCode" type="int">
<column name="zipCode" not-null="true" />
</property>
</class>
</hibernate-mapping>

有什么办法可以在 hbm 文件中的人员映射中添加唯一约束,以便我的名字和姓氏在数据库中是唯一的/

提前非常感谢。

4

1 回答 1

0

您可以制作包含last namefirst name使用<natural-id>元素的自然键。

请注意,<natural-id>只有当 Hibernate 生成表模式时,才有助于在自然键列上创建唯一约束hbm2ddl。Hibernate 不会 <natural-id>在运行时对列进行任何唯一性验证。

因此,如果您不打算使用 Hibernate 重新创建表模式,您可以简单地使用 DDL 手动为这些列添加唯一约束,并让数据库检查唯一性。

于 2012-04-19T19:06:44.457 回答