Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA one to one relationship where entity may not exist

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.

like image 252
Chris Williams Avatar asked Oct 05 '22 14:10

Chris Williams


1 Answers

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)
like image 189
evandongen Avatar answered Oct 10 '22 04:10

evandongen