有 3 pojo
即EmployeeMaster
(父类),Hr
和Personal
(EmployeeMaster的子类)。
然后我有 3 个单独的表,每个 pojo
,构造为:
create table emp_master(emp_code integer,emp_name text,emp_desig text,
emp_dept text,primary key(emp_code));
create table hr(emp_code integer,salary integer,hra integer,da integer,
taxes integer,grade text,foreign key(emp_code) references emp_master(emp_code));
create table personal(emp_code integer,address text,married bool,
foreign key(emp_code) references emp_master(emp_code));
emp_code
是 emp_master
的主键它是 hr
的外键和personal
表。
我构建了 3 个独立的 jsp
获取数据的表单。
以下是hibernate mapping
文件:
<hibernate-mapping>
<class name="pojo.EmployeeMaster" table="emp_master">
<id name="emp_code">
<generator class="assigned" />
</id>
<property name="emp_dept" />
<property name="emp_desig" />
<property name="emp_name" />
<joined-subclass name="pojo.Hr" table="hr">
<key column="emp_code" />
<property name="da" />
<property name="grade" />
<property name="hra" />
<property name="salary" />
<property name="taxes" />
</joined-subclass>
<joined-subclass name="pojo.Personal" table="personal">
<key column="emp_code" />
<property name="address" />
<property name="married" />
</joined-subclass>
</class>
</hibernate-mapping>
现在的问题是,我不想要任何null
行并想要提交相同的数据 emp_code
进入其他表即 hr
和personal
.
但是当我尝试将数据提交到 hr
时表 emp_code 101
,已存在于 master table
中我收到一条错误消息 Duplicate entry '101' for key 'PRIMARY'
.
如果我更改generator class to increment
在映射 xml 中,我得到一行包含空值的数据,用于从子类插入的数据。我想要的是具有相同 employee code
的三个表中的条目。 。我该怎么做呢 ?
最佳答案
您的 hibernate 映射建议您 EmployeeMaster
、HR
和 personal
形成一个层次结构,即 EmployeeMaster
是父级类,而 HR
和 Personal
是子类。
您想要实现的目标以及您的映射建议的内容存在问题。在上面的映射中,ID
可以映射到 HR
或 Personal
,但不能同时映射到两者。
您应该考虑将映射从INHERITANCE更改为ASSOCIATION。
根据您的映射 xml,您的 java 类应定义如下:
public class EmployeeMaster {}
public class HR extends EmployeeMaster{}
public class Personal extends EmployeeMaster{}
现在,您必须考虑如何将您的要求融入到上述模型中。如果情况并非如此,那么您别无选择,只能更改模型(以及 xml 映射)
关于java - 使用继承时存储 'employee code' 的公共(public)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17037279/