Reputation: 1703
Im strugglin with hibernate. I'm trying to delete object BUT I'm getting sql exception.
So first my mappings:
@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;
So I'm trying to delete meetup entity, but by doing that I dont want to delete coresponding Location entity. Now when I'm trying to remove meetup entity (entityManager.remove) I'm getting
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
The problem can be solved by changing Cascade type to "ALL" on mapping in meetup class, but then obviously my Location entity will be deleted too. And this is something I dont want to happen. So how could I achieve deleting meetup entity without deleting location entity?
Upvotes: 0
Views: 1400
Reputation: 21103
All you simply need to do is make sure you handle the removal of the MeetUp
as follows within the boundary of a transaction:
// 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 );
Given your model, there is no need to fudge with cascade operations for this use case.
Upvotes: 1