我对OnetoOne和ManyToOne(不是OneToMany)的区别感到困惑.
让我们假设我们有一个Person类和一个Department类.当我们说多个Person可以属于一个Department时,我们假设一个ManyToOne关系,并在Person类中添加一个DeptID列.这对我来说是有意义的,并如所说的那样奏效.
然而,如果我们说Person和Department是一对一的关系,这意味着一个人只有一个部门,一个部门只有一个人.然而,这就是问题所在.JPA仍然允许两个Person对象共享同一个部门.
Person Class:个
@Entity
@Table
public class Person {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
int id;
@Column
int age;
@Column(length = 20)
String name;
@Column(length = 20, nullable = true)
String cnic;
@Column(nullable = true)
boolean married;
@OneToOne
Department dep;
}
Department Class:个
@Entity
public class Department {
@Id
int Id;
@Column
String name;
}
Making two Persons with same Department:个
public void testOTO() {
System.out.println("Testing OTO");
Department dep = new Department(202, "CS");
depdb.saveAndFlush(dep);
Person p1 = new Person();
Person p2 = new Person();
p1.setDep(dep);
p2.setDep(dep);
db.saveAndFlush(p1);
db.saveAndFlush(p2);
}
我想问,OnetoOne和ManyToOne之间的区别只是语义上的,还是我错过了什么?