java - 如果我只有 ID,如何在 JPA2 中持久保存多对多集合?

标签 java hibernate jpa-2.0

这是我的多对多集合:

    @ManyToMany
@JoinTable(name="affiliated_databases",
        joinColumns=
        @JoinColumn(name="database_id", referencedColumnName="id"),
        inverseJoinColumns=
        @JoinColumn(name="affiliated_database_id", referencedColumnName="id")
)
public Set<Database> affiliatedOrgs;

在我的服务类方法中,我只有这个集合的 ID。 有没有什么好的解决方案可以保留这个集合而不从数据库中读取其元素?

我正在尝试做这样的事情:

 for (Long affId: affIds) {
            Database affDatabase = new Database();
            affDatabase.setId(affId);
            target.getAffiliatedOrgs.add(affDatabase);
        }
 dao.save(target);

这是工作,但是 1)它在我看来有点不优雅; 2)如果这个目标对象将来在某个地方使用,它可能会产生错误......或者也许这是一个很好的解决方案,我的怀疑是徒劳的?

那么有没有更优雅的方法来持久化这个集合,而不需要从数据库中读取它的所有对象,并且不会在将来引发错误。

最佳答案

您可能想使用EntityManager.getReference() 。它创建一个实体“代理”对象,并延迟获取其所有属性(如果需要)。

Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.

关于java - 如果我只有 ID,如何在 JPA2 中持久保存多对多集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42136056/

相关文章:

JAVA - 检查结果集中的 NULL 值

java - 如何在 SQL (JPA) 中使用带有 IN 运算符的嵌套 SELECT 语句?

java - Java 中的急切垃圾收集

java - DAO 如何映射 SQL 函数返回的字段?

java - JPA 乐观锁

java - 刷新与 jTable 绑定(bind)的 JPA 结果列表

sql - 这个在 SELECT 中带有子查询的 SQL 可以转换为 Hibernate 3.0.5 HQL 吗?

用于添加和查看引用表中的值的 JPA 注释

hibernate - JPA createQuery 或 @NamedQuery

java - hibernate实体中的必填字段