How to remove child objects from @ManyToMany relationship with lots of children in JPA and Hibernate

Let's say I have two objects: Organization and User. Each user can be a member of many organizations, and each organization can have many users.

@Entity public class User { @ManyToMany Set<Organization> organizations; //... } @Entity public class Organization { @ManyToMany(mappedBy="organizations") Set<User> users; //... } 

Now I want to delete the organization (for example, it has 1000 members). When a user has few organizations, this code is in order:

 void removeOrgFromUser(Integer userId,Integer orgId){ User user = session.load(User.class, userId); for (Organization org : user.organizations) { if(org.getId().equals(orgId)) user.organizations.remove(org); } session.update(user); } 

But when the number of organizations is 10,000, this solution does not have good performance.

How can i fix this?

+5
source share
1 answer

As I explained in this article , if you have more than 50 or 100 child entities, you should not display the collection.

Therefore, @OneToMany is misleading, because in reality @OneToFew makes more sense. Thus, when many tools are 1000 or 10000, displaying such a collection becomes a real performance problem.

In this case, just fold the @ManyToMany relationship to map the UserOrganization connection UserOrganization .

In this case, you only need 2 @ManyToOne associations in the connection table, and you can simply issue a bulk delete request as follows:

 delete from UserOrganization uo where uo.organization = :organization 

What is it!

+3
source

Source: https://habr.com/ru/post/1272753/


All Articles