0

I have the following two POJOs:

@Entity(name = "project") @Table(name = "project") public class Project { @Column(name = "identifier") @Id @GeneratedValue private Integer identifier; @ManyToMany(cascade = CascadeType.ALL) private Set<Member> members = new HashSet<Member>(); // --- constructors --- public Project() { } // --- getters --- public Integer getIdentifier() { return identifier; } public Set<Member> getMembers() { return members; } } 

and

@Entity(name = "member") @Table(name = "member") public class Member { @Column(name = "identifier") @Id @GeneratedValue private Integer identifier; @Column(name = "name", columnDefinition = "text") private String name; @ManyToMany(mappedBy = "members") private Set<Project> projects = new HashSet<Project>(); // --- constructors --- public Member() { } // --- getters --- public Integer getIdentifier() { return identifier; } public String getName() { return name; } public Set<Project> getProjects() { return projects; } } 

What is common practise do delete from a many-to-many relation? The following code works perfectly, but it generates a lot of overhead. First, there are some queries:

  1. 1 query to get the projects, triggered by member.getProjects()
  2. N queries to get all members of the each project, triggered by project.getMembers()

Second, the complete data set of the project (query 1) and member (query 2) is fetched, and not only the identifier.

final Member member = ...; for (final Project project : member.getProjects()) { project.getMembers().remove(member); } db.delete(member); 

Is it possible to do this more efficient without being forced to write ad-hoc queries?

1 Answer 1

1

Take a look here:

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

Additionally you have the option to use jpql statements to delete data:

http://docs.oracle.com/html/E24396_01/ejb3_overview_query.html#ejb3_overview_query_delete

But I think the first link is what you are looking for.

Sign up to request clarification or add additional context in comments.

2 Comments

I might be wrong, but the first link proposes what I am doing here. However, my concern is that it generated a lot of query/data overhead.
Well you'r right that will produce some overhead, but as far as I know this is the common way. However, did you try out the jpql solution? That should work with very few Statements.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.