gpt4 book ai didi

java - 删除实体时违反约束

转载 作者:行者123 更新时间:2023-12-01 09:25:10 26 4
gpt4 key购买 nike

我正在与 hibernate 作斗争。我正在尝试删除对象,但遇到 sql 异常。

首先是我的映射:

@Entity
public class Meetup {

@Id
@GeneratedValue
@Column
private long id;

@Column(nullable = false)
private ZonedDateTime dateAndTime;

@ManyToOne(fetch = FetchType.EAGER,cascade=CascadeType.PERSIST)
private Location location;

/////////////////////////

@Entity
public class Location {

@Id
@GeneratedValue
@Column
private long id;

@Column(nullable = false)
private String name;

@Column(nullable = false)
private double longitude;

@Column(nullable = false)
private double latitude;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "location")
private List<Meetup> meetups;

///////////////////////////////////////////////////////

@Entity
public class Match {
@Id
@GeneratedValue
@Column
private long id;

@ManyToMany(fetch = FetchType.LAZY, cascade=CascadeType.ALL)
private List<User> users = new ArrayList<>();

@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "meetup_id")
private Meetup meetup;

所以我试图删除聚会实体,但这样做我不想删除相应的位置实体。现在,当我尝试删除 meetup 实体 (entityManager.remove) 时,我得到

 constraint ["FKJRLUYUGNHRKYWSVSRE8VE9I9D: PUBLIC.MATCH FOREIGN KEY(MEETUP_ID) REFERENCES PUBLIC.MEETUP(ID) (1)"; SQL statement: delete from meetup where id=? [23503-192]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

可以通过在 meetup 类中的映射上将 Cascade 类型更改为“ALL”来解决该问题,但显然我的 Location 实体也会被删除。这是我不希望发生的事情。那么如何才能实现删除聚会实体而不删除位置实体呢?

最佳答案

您只需确保在事务范围内按如下方式处理 MeetUp 的删除:

// Get your meetup by identifier
final Meetup meetup = entityManager.find( Meetup.class, meetupId );

// cleanup the match associations with meetup
entityManager.createQuery( "FROM Match WHERE meetup = :meetup")
.setParameter( "meetup", meetup )
.getResultList()
.forEach( match -> { match.setMeetup( null ); } );

// remove meetup
entityManager.remove( meetup );

根据您的模型,无需针对此用例使用级联操作。

关于java - 删除实体时违反约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39893131/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com