Java – JPA one-to-one relationship, where the entity may not exist
I have many to one mapping between two entities (A and B, and a B can be associated with many as). I need to be able to obtain the ID of B on a (a.b_id), where the specific B entity does not exist in the database Is that 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 setting will eventually make hibernate try to create A.B_ ID holds a null value, which is not allowed:
Caused by: java.sql.BatchUpdateException: ORA-01400: cannot insert NULL into ("MY_SCHEMA"."A"."B_ID")
For clarity, I do not want an entity to be created if it does not already exist I just want to insert a without B in the database. There is no foreign key constraint between the two tables
Solution
I use the @ notfound annotation on the @ manytoone side to ensure that it does not cause any errors I haven't tried a two-way relationship yet
Note that this is not a hibernate specific comment!
Example:
@NotFound(action=NotFoundAction.IGNORE)