我正在与休眠斗争。我试图删除对象但是我得到了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;
所以我试图删除聚会实体,但通过这样做,我不想删除相应的位置实体。现在,当我试图删除聚会实体(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
可以通过将级联类型更改为&#34; ALL&#34;来解决问题。在meetup类中映射,但显然我的Location实体也将被删除。这是我不想发生的事情。那么如何在不删除位置实体的情况下实现删除聚会实体呢?
答案 0 :(得分:1)
您只需要确保在交易边界内按照以下方式处理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 );
鉴于您的模型,没有必要使用此用例的级联操作来捏造。