Collection cascade with detached entities

Hi, I have an entity with collection like below. And if I assign to this collection detached value and then call persist or flush on the owning entity. I get the exception below. This started to happen with Hibernate 6.2.13, version 5 didn’t have a problem with detached values. I think this is because of AbstractFlushingEventListener.getCascadingAction() returns PERSIST_ON_FLUSH instead of SAVE_UPDATE.
@beikov can you help or recommend what would be the ideal solution to this? We relied on hibernate 5 SAVE_UPDATE behavior, but with the PERSIST_ON_FLUSH we’re getting lot of issues. My question is if we’re incorrectly using hibernate with passing the detached object into collection or if this is a bug?

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.core.domain.BuyerGroupImpl
    @ManyToMany(targetEntity = BuyerGroupImpl.class, fetch = FetchType.LAZY)
    @JoinTable(
            name = "COMMUNITY_CATALOGUE_BUYER_GROUP",
            joinColumns = { @JoinColumn(name = "COMMUNITY_CATALOGUE_ID") },
            inverseJoinColumns = { @JoinColumn(name = "BUYER_GROUP_ID") }
    )
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.PERSIST})
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    protected Set<BuyerGroup> groups;

I think this is because of AbstractFlushingEventListener.getCascadingAction() returns PERSIST_ON_FLUSH instead of SAVE_UPDATE.

This is correct, the way how you bootstrap Hibernate affects which cascade is used. We were thinking about allowing people to configure this “jpaBootstrap” flag explicitly, but even if we add this at some point, it’s best if you start ensuring you only use managed entities in collections.

JPA demands this behavior, and since Hibernate ORM tries to align as much as possible with JPA semantics, you’re best advised to follow that sentiment.

Thanks @beikov, we’ve modified our code to reflect the JPA alignment in flush listener. We’ve relied too much on SAVE_UPDATE behavior in our test code.