How to properly delete a record from a database in one query. For example, when an entity uses the primary key of the parent entity using the @MapsId annotation, if the parent entry is deleted, it will swear that the parent's id is used in the child entity.
Code example :
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String name;
}
@Entity
public class UserDetails {
@Id
private long id;
private String phone;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private User user;
}
Here, when deleting a User using the JpaRepository delete method, an error will occur that the UserDetail uses the primary key User
CodePudding user response:
For that you need to delete all foreign keys with used by primary key
or by using cascade
After that use below
In JPA we can use deleteById
or by named query
DELETE FROM EMPLOYEE WHERE ID = ?1
or my native query
delete from employee where id = ?1
CodePudding user response:
First, are you sure the direction of the relation makes sense? I would have expected it to be the other way around, because the user ID and name seem to be the more basic info that you need more often.
Second, what you're doing seems like an attempt to optimize performance, because you could just as well store all the data in a single entity. Are you sure the optimization pays off? (I would guess not.) See Premature Optimization.
Third, if the relation was the other way around, you could modify the annotation to @OneToOne(cascade=CascadeType.ALL)
to let JPA automatically delete the other entity when the first is deleted.