Hibernate OneToMany与ORA-02291错误

时间:2015-08-20 08:39:23

标签: hibernate one-to-many ora-02291

当在OneToMany关系中持有具有其子项的实体时,我遇到了问题。 这是我的两个实体:

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

现在生成ORA-02291错误的持久化操作:

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

有什么想法解决这个问题吗?

感谢大家!

2 个答案:

答案 0 :(得分:0)

我认为你需要在地址表中删除@JoinColumn的name属性

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

}

你已经有了mapBy =&#34;用户&#34;来自用户方。

答案 1 :(得分:0)

我从昨天开始就陷入困境,但现在我找到了问题的解决方案。在我的情况下,错误是由于我有TRIGGERS将MY_SEQUENCE.nextval设置为其各自实体的表的PK。

然后,更改TRIGGER以验证实体中的:new.PK是否为null以设置它的解决方案。相反,如果它不为空,则可以理解SEQUENCE是从JPA设置为PK的。例如:

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;