简体   繁体   English

如何在一个查询中正确地从数据库中删除一条记录? JPA

[英]How to properly delete a record from a database in one query? JPA

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.例如,当实体使用@MapsId注解使用父实体的主键时,如果父条目被删除,它会发誓在子实体中使用父实体的id。

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这里,使用JpaRepository delete方法删除User时,会出现UserDetail使用主键User的错误

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在 JPA 我们可以使用deleteById

or by named query通过命名查询

DELETE FROM EMPLOYEE WHERE ID =?1从 ID =?1 的员工中删除

or my native query或者我的本机查询

delete from employee where id =?1从 id =?1 的员工中删除

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.我本来希望它是另一种方式,因为用户 ID 和名称似乎是您更经常需要的更基本的信息。

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.DELETE) or @OneToOne(cascade=CascadeType.ALL) to let JPA automatically delete the other entity when the first is deleted.第三,如果关系是相反的,您可以将注释修改为@OneToOne(cascade=CascadeType.DELETE)@OneToOne(cascade=CascadeType.ALL)以让 JPA 在删除第一个实体时自动删除另一个实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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