Victor L
Victor L

Reputation: 10230

Why does setting ManyToOne parent early causes flush to fail?

I am creating a JPA entity with a ManyToOne relationship. Why does having child.setParent(parent); cause the following fail during flush():

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

The test code that fails:

    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();

Entities:

@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;
}

If I remove child.setParent(parent); statement, then my code passes. Using OpenJPA 2.2.2

Upvotes: 0

Views: 95

Answers (1)

John Ament
John Ament

Reputation: 11723

I beleive your MapsId should be @MapsId("parentId") based on the class structure you've presented. The value of MapsId is an attribute, not a column name.

Upvotes: 1

Related Questions