java - JPA 在 ManyToOne 关系中持久化对象

标签 java hibernate jpa entity-relationship

我的数据库中有一个公司/员工 @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 的公司?

最佳答案

  • 在描述的情况下,Companyid 将在持久化 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/

相关文章:

java - 验证时如何将PDF注释与签名连接起来?

java - 在 Session.save() 之间交换行。输出发生什么变化。请参阅代码中的注释。我是java hibernate新手

java - JPA CriteriaQuery 是否需要 begin() 和 commit()?

java - 如何在python中使用递归从java代码中解析方法体?

java - Android EditText 符号必须保持在初始位置

java - 排除 apk 文件中的预定义资源

Spring,Spring Data JPA : org. hibernate.hql.internal.ast.QuerySyntaxException:测试未映射

java - 如何在 JUnit 测试中强制命中二级缓存?

java - 像 hibernate 这样的 ORM 框架在迭代结果集时是否实现任何类型的行映射器?

jpa - 如何在 DDD 中实现 Vaughn Vernon 关于聚合中引用的建议