R
R
Rokoss2022-04-06 00:23:27
Java
Rokoss, 2022-04-06 00:23:27

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.
@OnDelete(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".


Two Entities (no extra details).

@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;
}


AbstractBaseEntity is needed to override equals and hashcode and remove the common id field.

@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 question

Ask a Question

731 491 924 answers to any question