我正在尝试将非主键用作我的应用程序中的外键。这是场景:我有 EMPLOYEE 和 EMPLOYEE_PROPERTIES 表。Employee 和 Employee 属性之间存在一对多的关系。这是我的架构:
create table employee(
fname varchar2(100) not null,
lname varchar2(100) not null,
emp_id number not null
);
ALTER TABLE employee ADD constraint employee_pk PRIMARY KEY (fname, lname);
alter table employee add constraint employee_uniue unique (emp_id);
create table employee_property(
emp_prop_id not null,
emp_id number not null,
property_name varchar2(100) not null,
property_value varchar2(100) not null
);
ALTER TABLE employee_property ADD constraint employee_property_pk PRIMARY KEY (emp_prop_id);
ALTER TABLE employee_property ADD CONSTRAINT emp_prop_fk FOREIGN KEY (emp_id) REFERENCES employee(emp_id);
这是我的休眠映射 xmls: -----------------Employee------------------------
<hibernate-mapping>
<class name="com.persistence.vo.Employee" table="EMPLOYEE">
<composite-id>
<key-property name="fName" column="FNAME"/>
<key-property name="lName" column="LNAME"/>
</composite-id>
<property name="empId" type="long" access="field" unique="true">
<column name="EMP_ID" />
</property>
<set name="employeeProperties" table="employee_properties" lazy="false"
fetch="select" cascade="save-update, delete-orphan">
<key>
<column name="emp_id" not-null="true"/>
</key>
<one-to-many entity-name="com.persistence.vo.EmployeeProperty"/>
</set>
</class>
</hibernate-mapping>
--------员工属性------
<hibernate-mapping>
<class name="com.persistence.vo.EmployeeProperty" table="EMPLOYEE_PROPERTY">
<id name="empPropId" type="long">
<column name="EMP_PROP_ID" />
<generator class="assigned" />
</id>
<many-to-one name="employee" class="com.persistence.vo.Employee" fetch="select">
<column name="empId" not-null="true"/>
</many-to-one>
<property name="propertyName" type="java.lang.String">
<column name="PROPERTY_NAME" />
</property>
<property name="propertyValue" type="java.lang.String">
<column name="PROPERTY_VALUE" />
</property>
</class>
</hibernate-mapping>
------------Employee.java--------------
public class Employee {
private long empId;
private String fName;
private String lName;
private Set<EmployeeProperty> employeeProperties;
}
------------EmployeeProperty.java-------
public class EmployeeProperty {
private long empPropId;
private Employee employee;
private String propertyName;
private String propertyValue;
}
当我尝试访问员工时,我不断收到以下异常:原因:org.hibernate.MappingException:外键 (FKF28BCC4680C757C:EMPLOYEE_PROPERTY [emp_id])) 必须具有与引用的主键相同的列数 (EMPLOYEE [FNAME,LNAME] )
是否可以引用非主键作为您的外键?