问题
I have two domain classes with a many-2-many relationship between them, e.g. User and Group. There's a user2group table in the database to map this relationship. If I want to set User's Groups based on a list of Group IDs (which might come e.g. from a HTML form) do I really have to fetch the Groups first to update the User through setUsers(Set<Users>)
? I already have the Group IDs and they are actually the only information needed to update the mapping table...
I'm using Spring Data JPA and Hibernate as the provider.
回答1:
You can write a native query, but the whole point of ORM is to use it. You may not have to fetch the Group if the owning side of the relationship is on the User, but it's most common to define it on the Group. In this case, if you are going to use the ORM, yes, you have to fetch the Groups.
来源:https://stackoverflow.com/questions/9687865/jpa-manytomany-set-update-by-list-of-ids-instead-of-list-of-actual-objects