Search code examples
jakarta-eeeclipselinkjpa-2.0

EclipseLink @OneToOne relation CascadeType should not remove


I have two entity class, and there is a @OneToOne relation between them. There are also a foreign key in the database.

class Entity1 {
    @OneToOne(cascade = CascadeType.ALL, mappedBy = "entity1")
    private Entity2 entity2;
}

class Entity2 {
    @JoinColumn(name = "DB_FIELD_NAME", referencedColumnName = "ENTITY_1_PK")
    @OneToOne(optional = false)
    private Entity1 entity1;
}

As you can see there is cascade = CascadeType.ALL parameter. Of course, if I remove my entity1 object:

em.remove(entity1)

it's cascading to my entity2 and that object also removed from the database. My question is, how can I don't remove my entity2

What kind of CascadeType should I use?

Thank you!


Solution

  • Simply nothing. If you don't want to cascade, do not use cascade parameter, it's optional.

    class Entity1 {
        @OneToOne(mappedBy = "entity1")
        private Entity2 entity2;
    }
    
    class Entity2 {
        @JoinColumn(name = "DB_FIELD_NAME", referencedColumnName = "ENTITY_1_PK")
        @OneToOne(optional = true)
        private Entity1 entity1;
    }