Nesquik27
Nesquik27

Reputation: 254

Cannot remove jpa child entity by persistance remove

I can remove any row by plain HQL like

Query q = em.createQuery("DELETE FROM Cities WHERE id = :id");

But I want to remove It like

Cities city = em.getReference(Cities.class, 8);

    try {
        em.getTransaction().begin();
        em.remove(city);
        em.getTransaction().commit();
    }
    catch(RuntimeException e) {
        e.printStackTrace();
        em.getTransaction().rollback();
    }

And I got no warnings or errors

Models are simple

Countries (only OneToMany annotation)

@OneToMany(mappedBy = "country", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private List<Cities> cities;

Cities (only fk field)

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "country_id", nullable = false)
private Countries country;

Things which I were trying are:

1) trying to apply orphanRemoval = true
2) cascade = CascadeType.MERGE to Cities
3) em.refresh(city)

Upvotes: 0

Views: 110

Answers (1)

Chris
Chris

Reputation: 21165

You are removing a City, but what are you doing with the country's reference to that now removed city? If this is in the persistence unit, the cascade persist/merge option will cause it to be picked up and re-inserted, undoing your desired remove operation. You have to null out any references to the city before you can remove it. Your JPQL might work because you aren't loading anything into memory, so the Country (and its reference to the City) isn't there and so not checked when you commit. While it works, It isn't good to rely on

Upvotes: 1

Related Questions