I've got a many-to-one mapping between two entities (A and B, one B can be associated with many As) where I need the ability to have an ID for B on A (A.B_ID) where that particular B entity doesn't exist in the database. Is this possible?
A (simplified) example of our code:
@Entity
@Table(name = "A")
public class A implements java.io.Serializable {
// ...
private B b;
// ...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "B_ID")
public B getB() {
return this.b;
}
// ...
}
@Entity
@Table(name = "B")
public class B implements java.io.Serializable {
// ...
private Set<A> as = new HashSet<A>( 0 );
// ...
@OneToMany( fetch = FetchType.LAZY, mappedBy = "b" )
public Set<A> getAs() {
return this.as;
}
// ...
}
This basic setup ends up with Hibernate trying to save a null value for A.B_ID and that's not allowed:
Caused by: java.sql.BatchUpdateException: ORA-01400: cannot insert NULL into ("MY_SCHEMA"."A"."B_ID")
For clarification, if the entity doesn't already exist, I don't want it to be created. I'd just want A to be inserted with no B in the db. There is no foreign key constraint between the two tables.
I use a @NotFound
annotation on the @ManyToOne
side to make sure that it won't causes any errors. I haven't tried it yet with a bidirectional relationship though.
Please not that this is a Hibernate specific annotation!
Example:
@NotFound(action=NotFoundAction.IGNORE)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With