我正在创建一个具有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的值是一个属性,而不是列名。

10-08 13:56