user1260928
user1260928

Reputation: 3439

How to delete child entity in a one-to-many relationship

I'm working on an application with RESTful API (Spring MVC) and JPA (Spring Data JPA repository) in the backend and AngularJS in the frontend.
I have two classes: Client and Address, one client can have several addresses.

My problem is that I have an error while deleting one address. Here are my two entities:

@Entity
@Table(name = "T_CLIENT")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Client implements Serializable {
    ...
    @OneToMany(mappedBy = "client", fetch = FetchType.EAGER)
    @JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<Adresse> adresses = new HashSet<>();
    ...
}

@Entity
@Table(name = "T_ADRESSE")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Adresse implements Serializable {
    ...
    @ManyToOne
    private Client client;
    ...
}

My web resource method to delete an address:

@RequestMapping(value = "/rest/adresses/{id}",
        method = RequestMethod.DELETE,
        produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public void delete(@PathVariable Long id) {
    adresseRepository.delete(id);
}

Let's say I want to delete Address with id = 9. After the deletion is done I am loading the Client with his addresses and I'm getting this error:

[ERROR] org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find com.myapp.domain.Adresse with id 9;
nested exception is javax.persistence.EntityNotFoundException: Unable to find com.myapp.domain.Adresse with id 9] with root cause javax.persistence.EntityNotFoundException: Unable to find com.myapp.domain.Adresse with id 9

My guess is that I'm not deleting the entity Address the proper way.

Upvotes: 0

Views: 665

Answers (1)

canals
canals

Reputation: 483

First of all I don't know why you have at class level and field level the same annotation in Client class: - @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)

You can just leave at field level if you need it.

Give a try commenting out this cache strategy annotation from Client class and if it works you have to review your cache configuration.

Hope it helps.

Upvotes: 1

Related Questions