简体   繁体   中英

How to update a collection field in entity using Spring Data JPA?

Let's say I have two entities, with @ManyToMany relation between their fields. The first entity called Pack :

@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.ALL})
    @JoinTable(name = "card_in_pack",
            joinColumns = {@JoinColumn(name = "pack_id")},
            inverseJoinColumns = {@JoinColumn(name = "card_id")})
    private Set<Card> cards = new HashSet<>();

The second one called Card :

@ManyToMany(mappedBy = "cards")
private Set<Pack> packs = new HashSet<>();

I have a controller, in which I want to add new Card entity to the set in Pack entity, and then I want to save it all to my DB with relations of course.

@PostMapping("/packs/{namePack}")
    public String addCard(@Valid Card card, @PathVariable String namePack, @AuthenticationPrincipal User user) {
            //Assume I got a Pack instance with name pack

            card.setAuthor(user);
            pack.addCard(card);
            packRepo.save(pack);

            return "pack";
        }
    }

Looks like every time I try to call packRepo.save(pack) method, it takes all the Card entities that are in the Pack entity and saves all of them to DB as a new ones, even if some of them already exist in my DB. I want it to check if Pack entity has a set of cards entities, it should check if each card with such IDs already exists in the DB, and add only new ones. I tried clearing the set and then add just the new elements I want to save, but then it just deleted everything that was not in the cuurent pack state from DB and add only new ones


I want the nicest way to save a @ManyToMany related Set so, that it won't create a new duplicate instances in my DB

The way I got the pack was really bad, I will not even show you this)

What helped is : moving all your repository logic from controllers to services, and mark it with @transactional annotation!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM