【发布时间】:2014-01-17 04:48:15
【问题描述】:
我正在学习 jpa 中的映射并阅读有关 ManyToOne 和 OneToOne 映射的信息。场景是
- 许多员工可以属于一个部门。即员工和部门之间的多对一
- 一名员工与一张办公桌相关联。即员工和办公桌之间的 OneToOne。
我已经将这些字段映射如下
@ManyToOne
@JoinColumn(name = "iddepartment")
private Department department;
@OneToOne
@JoinColumn(name = "iddesk")
private Desk desk;
根据 Mastering Java Persistence API 一书,OneToOne 映射用作唯一外键。因此,在我的示例中,应为一个员工记录分配特定的办公桌 ID。但是,即使我创建了多个员工并为他们分配了同一张办公桌,它也会被插入到数据库中。那么这里的 ManyToOne 和 OneToOne 有什么区别呢?根据我的说法,他们的行为方式相同。
我将实体持久化如下
/* Create EntityManagerFactory */
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("JPAExamples");
/* Create EntityManager */
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
Employee employee;
employee = new Employee();
employee.setFirstname("pranil");
employee.setLastname("gilda");
employee.setEmail("sdfsdf");
Department department = em.find(Department.class, 1); // retrieves
// department
// from database
employee.setDepartment(department);
Desk desk = em.find(Desk.class, 1); // retrieves desk from database
employee.setDesk(desk);
em.persist(employee);
transaction.commit();
employee = new Employee();
employee.setFirstname("prasad");
employee.setLastname("kharkar");
employee.setEmail("dsfsdf");
/* Now setting the same department for another employee which is fine because
* there is ManyToOne relationship betweem employee and department */
employee.setDepartment(department);
/*
* Here is my doubt. Even if I set the same desk for another employee. THe insertion
* is fine. Shouldn't the OneToOne relationship between Employee and Desk restrict employee
* table having duplicate foreign key for both employees?
*
* If that is not true, then what is the difference between ManyToOne and OneToOne in this case?
* */
employee.setDesk(desk);
transaction.begin();
em.persist(employee);
transaction.commit();
注意:我不是从实体生成表。
所以我的问题是:
- JPA OneToOne 批注没有将唯一外键约束放在员工表上。这是预期的结果吗?
- 如果这是预期的,那么为什么 ManyToOne 和 OneToOne 关系之间没有任何区别?
编辑:
根据提供的答案,我将其创建为双向关系。它给出了相同的结果。另外,我还添加了unique = true。这没有任何区别
课桌课
@OneToOne(mappedBy = "desk")
private Employee employee;
在 Employee 类中
@OneToOne
@JoinColumn(name = "iddesk", unique = true)
private Desk desk;
我错过了什么严重的事情吗?
【问题讨论】:
-
请添加更多信息。 Desk 实体中的 OneToOne 是如何注解的?您如何创建和保存它们?
-
@kostja 我已经添加了一些关于问题先生的信息。 OneToOne 映射在这里是单向的。所以没有必要在 Desk 类中注释 OneToOne
标签: jpa-2.0 one-to-one many-to-one