7

I have a class A{Set b .....} which holds references of class B as Set. It is one to many relationship. Both class have sequencer in oracle. I put cascade to all in hibernate annotations. When i save class A, it gives me error that cannot insert null B.a_id . A-id is not nullable in my database. How can i persist this relationship.

Cœur
  • 37,241
  • 25
  • 195
  • 267
dmay
  • 1,305
  • 6
  • 21
  • 31
  • Show us some more code, please.. This is too little information to answer your question. – Tim Sep 16 '10 at 07:56
  • I annotated class b in A as @OneToMany @Cascade({CascadeType.ALL}) @JoinColumn(name="A_ID") private Set b; Annotated class B as usual. This is a unidirectional relationship from A->B. a_id column in table B is not nullable. When hibernate tries to save class B, it not able to find value for a_id. When i remove this mapping, then class A is successfully saved with auto generated value. – dmay Sep 16 '10 at 08:13

2 Answers2

21

This is a unidirectional relationship from A->B. a_id column in table B is not nullable. When hibernate tries to save class B, it not able to find value for a_id.

Well, did you try to make the JoinColumn non nullable?

@OneToMany 
@Cascade({CascadeType.ALL}) 
@JoinColumn(name="A_ID", nullable=false)
private Set<B> b;

See also

Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
  • Thanks a lot, It is working now. It is foolish to not see all attributes. – dmay Sep 16 '10 at 09:38
  • Now it is successfully working. I can one insert statement into A and one for B ,then update statement for table B. Since insert statement doesn't throw exception i wonder if hibernate insert temporary values into a_Id. – dmay Sep 23 '10 at 15:34
  • If i change the mapping from OnetoMany to OnetoOne, then it again give cannot insert null sql exception. How can i then persist OnetoOne mapping. – dmay Sep 24 '10 at 07:24
2

I ran into the same problem and solved it by using the mappedBy attribute of the @OneToMany annotation in Class A:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "m_a")
private Set<B> b;

Here, m_a is the field in Class B that refers to Class A:

@JoinColumn(name = "aId", nullable = false)
@ManyToOne
private A m_a;

This way, the @JoinColumn is only specified in one place, no duplicated code.

Jos
  • 1,015
  • 2
  • 13
  • 25