简体   繁体   中英

JPA @OneToOne relationship deletion

I have the following @OneToOne relationship:

@Entity
public class CarUser {
    @OneToOne
    @JoinColumn(name = "use")
    private User user;
}

@Entity
public class User {
}

Basically, the User is in the core model and CarUser is in an extension model. And User shouldn't know anything about CarUser (I cannot define an inverse relation on it).

The question is When I delete the User, is there anyway I can cascade delete the CarUser as well?

By definition, if you want to state that "User shouldn't know anything about CarUser" you can't get the persistence layer to cascade for you.

You don't necessarily need to make that statement, though - it may not be a correct design understanding. It's reasonable for entities, within the same database schema, to know about each other.

Let's put it this way -- even though (in an manufacturing/accounting system) CostingModule and LedgerModule are in different modules, they absolutely are expected to communicate and interact.

You can also do it with a foreign-key constraint in the database instead, or with triggers.

alter table CARUSER add constraint CARUSER_USER foreign key (ID) 
  references "USER" (ID) on delete cascade;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM