Answer the question
In order to leave comments, you need to log in
UPDATE DELETE violates foreign key constraint ( spring data jpa ), ondelete doesn't help, how to solve?
Here are two Entities, Dish and OrderItem related OneToMany and ManyToOne.
When trying to remove Dish - that's the problem.
(action = OnDeleteAction.CASCADE)
Doesn't solve the problem.
Here is the error in full:
org.postgresql.util.PSQLException: ERROR: UPDATE or DELETE on table "dish" violates foreign key constraint "fks7aplknkrukmckr29wijlvcy1" on table "order_item"
Details: Key (id)=(602) is still referenced in table "order_item".
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class Dish extends AbstractBaseEntity{
@OnDelete(action = OnDeleteAction.CASCADE)
@OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "dish")
@ToString.Exclude
private List<OrderItem> orderItems;
}
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class OrderItem extends AbstractBaseEntity{
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "dish_id")
private Dish dish;
}
@MappedSuperclass
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class AbstractBaseEntity {
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "seq_gen")
@SequenceGenerator(
name = "seq_gen")
protected long id;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractBaseEntity that = (AbstractBaseEntity) o;
if (id == 0) return false;
return id == that.id;
}
@Override
public int hashCode() {
if (id != 0) {
return Objects.hash(id);
} else {
return super.hashCode();
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question