E
E
Egor Lepikhin2020-02-13 12:40:11
Java
Egor Lepikhin, 2020-02-13 12:40:11

How to properly cascade remove child elements in hibernate?

I have a Device entity, with a OneToMany relationship to a Sensor entity. I need to make sure that when deleting a Device, all Sensors associated with it are deleted. Now the links are described as follows:

device.class
@OneToMany(mappedBy = "device", orphanRemoval = true, cascade = CascadeType.ALL)
    private List<Sensor> sensors;


Sensor class
@JoinColumn(name = "device_id")
    @ManyToOne(fetch = FetchType.LAZY)
    private Device device;


When trying to remove all Device from the table, an error pops up:
mistake
ERROR: ОШИБКА: UPDATE или DELETE в таблице "devices" нарушает ограничение внешнего ключа "fk834yqd4p6g9s2b6ufnba8bxrs" таблицы "sensors"
DETAIL: На ключ (id)=(18) всё ещё есть ссылки в таблице "sensors".
SQL state: 23503

If you look at the table creation code in PGAdmin, then for some reason ON UPDATE NO ACTION is written there
creating devices
CREATE TABLE public.devices
(
id bigint NOT NULL,
last_connection timestamp without time zone,
name character varying(255) COLLATE pg_catalog."default",
type character varying(255) COLLATE pg_catalog."default",
owner_id bigint,
CONSTRAINT devices_pkey PRIMARY KEY (id),
CONSTRAINT fkc610qimpcb4kdm60lpxdccmlr FOREIGN KEY (owner_id)
REFERENCES public.users (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
WITH (
OIDS = FALSE
)

Tried to replace with @Cascade annotation, but no result

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DDwrt100, 2020-02-13
@DDwrt100

try via @Fetch

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question