Hibernate OneToMany with ORA-02291 error

308 views Asked by At

I have a problem when persist an entity with its childs in OneToMany relationship. Here my two entity:

@Entity
@Table(name="USER")
public class User implements Serializable {
  ...
  @Id
  @Column(name="ID_USER")
  private String idUser;

  @OneToMany(mappedBy="user", cascade=CascadeType.PERSIST)
  private List<Address> address;

  public List<Address> getAddress() {
     return this.address;
  }

  public void setAddress(List<Address> address) {
     this.address = address;
  }

  public Address addAddress(Address address) {
     getAddress().add(address);
     address.setUser(this);

     return address;
  }

  public Address removeAddress(Address address) {
     getAddress().remove(address);
     address.setUser(null);

     return address;
  }
  ...
}

@Entity
@Table(name="ADDRESS")
public class Address implements Serializable {
    ...


   @EmbeddedId
   private AddressPK id;

    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name="ID_USER", insertable=false, updatable=false, nullable=false)
    private User user;

    public User getUser() {
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

@Embeddable
public class AddressPK implements Serializable {
   ...
   @Column(name="ID_USER", insertable=false, updatable=false)
   private String idUser;
   ...
}

And now the persist operation that generate ORA-02291 error:

User u = new User();
u.setAddress(new ArrayList<Address>());

u.set...

Address a1 = new Address();
a1.set...
u.addAddress(a1);

Address a2 = new Address();
a2.set...
u.addAddress(a2);

entityManager.persist(u);

Any idea to fix this problem?

Thanks to everyone!

2

There are 2 answers

1
Tony Vu On

I think you need to remove the name attribute of @JoinColumn to in the Address table

@Entity
@Table(name="ADDRESS")
public class Address implements Serializable {
...
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(insertable=false, updatable=false)
private User user;

public User getUser() {
    return this.user;
}

public void setUser(User user) {
    this.user = user;
}

}

You already had mappedBy="user" from User side.

0
jmoran On

I was stuck in this since yesterday but now I found the solution to my problem. In my case, the error was due to I had TRIGGERS to set up MY_SEQUENCE.nextval to the PK of the table of its respective entity.

Then, the solution to change the TRIGGER to validate if the :new.PK from the entity is null to set it up. In contrary, if it's not null, it's understood that the SEQUENCE was set up to the PK from JPA. For example:

create or replace TRIGGER "MYSCHEMA"."TGR_MYTABLE_INSERT"
  before insert on MYTABLE
  for each row
  begin
  if :new.PK_MYTABLE is null then
    select SEQ_MYTABLE.nextval
    into :new.PK_MYTABLE
    from dual;
  end if;
  end;