egzaell
egzaell

Reputation: 195

Hibernate throws Cannot delete or update a parent row exception

While trying to delete item from db, hibernate throws exception:

Cannot delete or update a parent row: a foreign key constraint fails (`ticketer`.`UserOrder_Ticket`, CONSTRAINT `FKiyeesx6teiqckayn6agqw5b58` FOREIGN KEY (`tickets_id`) REFERENCES `Ticket` (`id`))
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

My Entities:

Ticket:

@Entity
public class Ticket {

@Id
@GeneratedValue
private Long id;

@OneToOne(cascade = CascadeType.ALL)
private Event event;

private String number;

private BigDecimal price;
}

UserOrder:

@Entity
public class UserOrder {

@Id
@GeneratedValue
private Long id;

@OneToMany(cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.FALSE)
private List<Ticket> tickets;

@OneToOne
private User user;

private BigDecimal price;
private PaymentStatus paymentStatus;
private LocalDateTime orderDate;
}

My database has tables connecting entities (standard for hibernate). Is there any possible solution to make it work? I'm using MySql.

Upvotes: 0

Views: 540

Answers (1)

Marcin46
Marcin46

Reputation: 120

If you want to delete UserOrder object firstly you need to remove relations between this UserOrder object and all Ticket objects which has relations with it.So I think you need to create UserOrder object in your Ticket class with ManyToOne annotation. Then set this field to null before you delete object which is there and in UserOrder class set tickets value also to null.

Upvotes: 1

Related Questions