Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 16420

JpaRepository.deleteAll() not working without calling JpaRepository.count()

$
0
0

I have 3 tables with 1:N relations, something like:

create table tbl1(    id bigserial primary key    name varchar unique not null    ...);create table tbl2(    id bigserial primary key,    tbl1_id bigint not null,    constraint tbl2_1_fk foreign key(tbl1_id) references tbl1.id    ...);create table tbl3(    id bigserial primary key,    tbl2_id bigint not null,    constraint tbl3_2_fk foreign key(tbl2_id) references tbl2.id    ...)

And entities for them:

@Entity@Table(name="tbl1")public class Ent1 implements Serializable {...    @OneToMany(mappedBy = "ent1", fetch = FetchType.LAZY,         cascade = CascadeType.ALL, orphanRemoval = true)    private List<Ent2> ent2 = new ArrayList<>();...}@Entity@Table(name="tbl2")public class Ent2 implements Serializable {...    @OneToMany(mappedBy = "ent2", fetch = FetchType.LAZY,         cascade = CascadeType.ALL, orphanRemoval = true)    private List<Ent3> ent3 = new ArrayList<>();    @ManyToOne(fetch = FetchType.LAZY,         cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})    @JoinColumn(name = "tbl1_id", nullable = false)    private Ent1 ent1;...}@Entity@Table(name="tbl3")public class Ent3 implements Serializable {...    @ManyToOne(fetch = FetchType.LAZY,     cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})    @JoinColumn(name = "tbl2_id", nullable = false)    private Ent2 ent2;...}

The problem is, that I have the code that does some "import" by retrieving data from some external source and inserting it in these tables. Before importing I delete data from all three tables, then insert new, like this:

ent3Repository.deleteAll(); // Added that because of a problement2Repository.deleteAll(); // Added that because of a problement1Repository.deleteAll();...// ent1Repository.count();...Ent1 ent1=new Ent1();// Set ent1 fields hereent1Repository.save();

But, if tbl1 contains data, like a row with the name='name1', when I try to persist an entity with the same name, I'm getting an exception that unique constraint violated for the field "name". Like, data weren't deleted. But, if I call ent1Repository.count() right after deletion (which I did for checking), it returns 0 and (the most weird thing for me) insertion is working without exceptions then.

Please help - I probably don't understand something simple. Why it is working this way? How and why calling count() helps?

Thank you!


Viewing all articles
Browse latest Browse all 16420

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>