JPA issue 2 attributes mapped to same column InvalidStateException: Attempt to set column to two different values

1.8k views Asked by At

I have the following problem,

I have the folowing classes:

class C(){
    ...

    @ManyToOne
    @JoinColumns({
        @JoinColumn(name = "B_FK", referencedColumnName = "B_ID"),
        @JoinColumn(name = "A_FK", referencedColumnName = "A_ID")})
    private B b = null;

    @ManyToOne
    @JoinColumn(name = "A_FK")
    private A a = null;
}

EDIT:

@Embeddable
class bPK(){

  @Column(name = "B_ID")
  private String bId;

  @Column(name = "A_ID")
  private String aId;
}

class B(){

    @EmbeddedId
    private bPK b_Pk = null;

    @ManyToOne   
    @MapsId(value = "aId")
    @JoinColumn(name = "A_ID")
    public A a;
}

class A(){
    @Id
    @Column(name = "A_ID")
    public String aId;
}

Class B has a composite key and we created the database scheme first, so we have to define the column names for mapping.

The problem now is that if we persist an instance of class C as like this:

C c = new C();
A a = new A();
a.setId("TEST_ID");
c.setA(a);

em.persist(c); 

Then we get the following error:

Caused by: <openjpa-2.2.0-r422266:1244990 fatal user error> org.apache.openjpa.persistence.InvalidStateException: Attempt to set column "C.A_FK" to two different values: (null)"null", (class java.lang.String)"TEST_ID" This can occur when you fail to set both sides of a two-sided relation between objects, or when you map different fields to the same column, but you do not keep the values of these fields in synch.

As the attribute b is null and the value for a is set, jpa tries to set A_FK to null for b and to "TEST_ID" for a.

It works fine if a and b are set or if both are null, but not if only one of them is set.

Is there a solution to fix this problem? We expected that in case b is null the JoinColumns are ignored or that there is any option to disable them in case the annotated attribute is null.

We use OpenJPA 2.2.0.

0

There are 0 answers