我正在研究jpa中的映射并阅读有关ManyToOne
和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();
注意:我不是从实体生成表格。
所以我的问题是:
编辑:
根据提供的答案,我将其创建为双向关系。它给出了相同的结果。另外,我还添加了unique = true
。这没有任何区别
在课堂课程
@OneToOne(mappedBy = "desk")
private Employee employee;
并在Employee类
中@OneToOne
@JoinColumn(name = "iddesk", unique = true)
private Desk desk;
我错过了一些严肃的事吗?
答案 0 :(得分:0)
您有一个单向的@OneToOne映射。如果您在“拥有”端设置了mappedBy属性的双向@OneToOne映射,则行为将符合预期。
E.g。在Employee对象中
@OneToOne(mappedBy="employee")
Desk desk
在Desk对象中
@OneToOne
Employee employee