JPA is a one to one relationship where an entity cannot exist

I have a multi-valued mapping between two objects (A and B, one B can be associated with many As), where I need the ability to have an identifier for B on A (A.B_ID), where this particular object B does not exist in the database. Is it 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 with Hibernate trying to save a null value for A.B_ID, and this is not allowed:

Caused by: java.sql.BatchUpdateException: ORA-01400: cannot insert NULL into ("MY_SCHEMA"."A"."B_ID")

For clarification, if an entity does not exist yet, I do not want it to be created. I just want A to be inserted without B in db. There is no foreign key constraint between the two tables.

+5
source share
1 answer

@NotFound @ManyToOne, , . .

, , Hibernate!

:

@NotFound(action=NotFoundAction.IGNORE)
+3

All Articles