java - 为什么过早设置 ManyToOne 父级会导致刷新失败?

标签 java jpa openjpa

我正在创建一个具有 ManyToOne 关系的 JPA 实体。为什么 child.setParent(parent); 会在 flush() 期间导致以下失败:

org.apache.openjpa.persistence.ArgumentException: Missing field for property "parent_id" in type "class test.ChildPrimaryKey".

失败的测试代码:

    Parent parent = new Parent();
    Child child = new Child();
    ChildPrimaryKey childPrimaryKey = new ChildPrimaryKey();
    childPrimaryKey.setLookupId(1);
    child.setId(childPrimaryKey);
    child.setParent(parent); // <-- FAIL because of this

    // Begin transaction
    entityManager.clear();
    entityManager.getTransaction().begin();

    LOGGER.info("Persisting parent without child.");
    entityManager.persist(parent);

    LOGGER.info("Updating parent with child.");
    childPrimaryKey.setParentId(parent.getId());
    parent.getChildren().add(child);
    entityManager.merge(parent);

    // Fail happens at flush
    entityManager.flush();

实体:

@Embeddable
public class ChildPrimaryKey {
    @Column(name = "lookup_id")
    private int lookupId;

    @Column(name = "parent_id")
    private long parentId;
}

@Entity
@Table(name = "child")
public class Child {

    @EmbeddedId
    private ChildPrimaryKey id;

    @MapsId("parent_id")
    @ManyToOne
    private Parent parent;
}

@Entity
@Table(name = "parent")
public class Parent {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Child> children;
}

如果我删除 child.setParent(parent); 语句,那么我的代码就会通过。使用 OpenJPA 2.2.2

最佳答案

根据您提供的类结构,我相信您的 MapsId 应该是 @MapsId("parentId")MapsId 的值是一个属性,而不是列名。

关于java - 为什么过早设置 ManyToOne 父级会导致刷新失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18433339/

相关文章:

java - 使用 JPA 时如何高效地找出新对象自动生成的 ID?

java - 模式是否定义元素数量?

java - 打开AL空指针异常

java - 如何连接JPA实体类? (一对多/多对一)

java - 如何确保 OpenJPA 中的非托管/托管对象身份?

java - 有人(成功)使用 Openjpa 和 Glassfish 4 了吗?

java - 在 ThreadLocal 实例中获取 volatile 变量的目的

java - 17 :42:55. 7385459 如何在java中制作这个日期格式

java - 每个具有不同 ID 名称的类继承的 JPA 表

hibernate - 在 JPQL 查询中应用新的 map() 函数来检索包含列详细信息的结果