dmay
dmay

Reputation: 1315

cannot insert null in one to many relationship hibernate annotation

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.

Upvotes: 8

Views: 32896

Answers (3)

Alain Cruz
Alain Cruz

Reputation: 5097

For anyone having a similar issue, additionally to the marked as correct asnwer, you must set the parent entity in each child. Otherwise you will get Cannot insert the value NULL into column 'X'. So, using the above example.

for (B b : listOfB) b.setA(A); // Here you must save the reference to the parent.

Also, if you want you can have the children's foreign column on the entity by adding the following annotation.

@Column(insertable = false, updatable = false)
private Long aID;

Upvotes: 0

Jos
Jos

Reputation: 1089

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.

Upvotes: 2

Pascal Thivent
Pascal Thivent

Reputation: 570585

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

Upvotes: 22

Related Questions