在我的项目中我有例如一个Employee
,其中包含多个Mobile
,其中包含其他属性,例如
Jon Doe, +911, private
Jon Doe, 123456, company
Jon Doe, 8978, company,
Mara Smith, 7888, private
Mara Smith, 458, company
因此我创建了
@Entity
public class Employee {
@Id
private int id;
@OneToMany(mappedBy="emp")
private List<Mobile> lstMobiles;
...
}
和Mobile
我有
@Entity
@IdClass(MobileKey.class)
public class Mobile {
@Id
private String phoneNo;
@Id
@JoinColumn(name = "emp_id")
private Employee emp;
...
}
class MobileKey{
private String phoneNo;
private int emp;
....
}
数据库包含表Employee
,Mobile
。表Mobile
前两列是
到目前为止没什么特别的,除了数据库有外部约束,即emp_id必须存在于表Employee
中。否则,phoneNo没有多大意义。
我现在面临的主要问题是我需要存储Jon Doe
或Mara Smith
。如果我使用例如。
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
}
有一些Autowired
变量,例如employeeRepo.save(newEmployee)
比我从数据库中获得违反约束。这是因为在表中创建Mobile
之前尝试插入Employee
: - (
我想Employee
和Mobile
的设计在某种程度上是错误的 - 尤其是列表和关系。但也可能与Spring-Data配置有关。