In this scenario I use unidirectional @ManyToOne relationship like the following:
@Entity
public class Shop {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String shopName;
}
@Entity
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "shop_id")
private Shop shop;
private String itemName;
}
@Repository
public interface ShopRepository extends JpaRepository<Shop, Long> {
}
@RestController
public class ShopController {
@Autowired
private ShopRepository shopRepository;
@DeleteMapping("/deleteShop")
private void deleteShop(@RequestParam Long id) {
shopRepository.deleteById(id);
}
}
When I try to delete the shop, I get below exception
org.postgresql.util.PSQLException: ERROR: update or delete on table "shop" violates foreign key constraint "fkedwdh6wdv6fqnyf914m5mt28i" on table "item"
Detail: Key (id)=(2) is still referenced from table "item".
Expected:
It should delete child data item when I delete parent data shop.