Moonlit
Moonlit

Reputation: 5409

JPA persist Object with cascase relation and then delete it (hibernate)

I have the following bidirectional 1:n relationship between A user entity and a job entity:

User class:

... 
    @OneToMany(mappedBy = "user",cascade={CascadeType.PERSIST}) 
    public Collection<Job> getJobs() { 
        return jobs; 
    } 

public void addJob(Job j) { 
    jobs.add(j); 
    j.setUser(this);
} 
...  

Job class:

// Job class 
... 
@ManyToOne 
    public User getUser() { 
        return user; 
    } 

Now saving a User object (and let hibernate automatically save the job entity) works... Then when i want to delete the job entity from the db i get an exception ....

        User user = new User();
        user.addJob(new Job());


        entityManager.getTransaction().begin();
        entityManager.persist(user);
        entityManager.getTransaction().commit();

        Job j = entityManager.find(Job.class, 1L);

        entityManager.getTransaction().begin();
        entityManager.remove(j);
        entityManager.getTransaction().commit();

Exception:

Exception in thread "main" javax.persistence.RollbackException: Error while committing the transaction
Caused by: javax.persistence.EntityNotFoundException: deleted entity passed to persist: [dst1.model.Job#<null>]

why does this happen? btw. when i explicitly call persist with the job object the problem does not occur... but i don't want to persist job seperately, but let hibernate persist them (with cascade, which actually works....)

thx

Upvotes: 0

Views: 1437

Answers (1)

barsju
barsju

Reputation: 4446

You need to remove the job from the user when you delete the entity:

    entityManager.getTransaction().begin();
    j.getUser().getJobs().remove(j);
    entityManager.remove(j);
    entityManager.getTransaction().commit();

Or by your own suggestion: Add orphanRemoval=true on the jobs collection.

Upvotes: 1

Related Questions