我的数据库中有一个公司/员工 @OneToMany
关系定义为:
@Entity
public class Employee {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@ManyToOne @JoinColumn(name="companyid")
Company company;
....
}
@Entity
public class Company {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
...
}
现在我要将新创建的员工添加到一家独立的公司。我使用的代码是这样的:
Company company = em1.find(Company.class, 555L);
em1.close();
EntityTransaction et = em2.getTransaction();
et.begin();
Employee employee = new Employee();
employee.company = company;
em2.persist(employee);
et.close();
这样可以吗?
hibernate 是要将公司合并到第二个 EntityManager 还是只使用它的 id 并保留员工对象?
hibernate 可能会以某种方式复制我的公司对象或抛出异常,表明数据库中已存在具有相同 ID 的公司?
最佳答案
- 在描述的情况下,
Company
的id
将在持久化Employee
对象时使用,但Company
本身不会被合并(注意Employee
是关系的拥有方) - 如果
Company
是 transient 的而不是分离的,您将收到“对象引用未保存的 transient 实例”错误 - 如果使用
cascade = CascadeType.PERSIST
,您将收到“分离的实体传递给持久化”错误。
来自 JPA 规范:
If X is a managed entity, it is synchronized to the database.
- For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade= ALL, the persist operation is applied to Y.
- For any entity Y referenced by a relationship from X, where the relationship to Y has not been annotated with the cascade element value cascade=PERSIST or cascade= ALL:
- If Y is new or removed, an IllegalStateException will be thrown by the flush operation (and the transaction marked for rollback) or the transaction commit will fail.
- If Y is detached, the semantics depend upon the ownership of the relationship. If X owns the relationship, any changes to the relationship are synchronized with the database; otherwise, if Y owns the relationships, the behavior is undefined.
关于java - JPA 在 ManyToOne 关系中持久化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4290520/