quarkusio / quarkus

Quarkus: Supersonic Subatomic Java.
https://quarkus.io
Apache License 2.0
13.55k stars 2.62k forks source link

Add Support for `merge(Entity)` in `PanacheRepositoryBase` #33817

Open clun opened 1 year ago

clun commented 1 year ago

Description

In a project, I had to create a few entities in one go, and persist() or persistAndFlush() were not good enough i got "Detached entity passed to persist" error message

@Entity
@Table(name = "Table_A")
public class EntityA {
    @Id
    @GeneratedValue(generator="uuid-generator")
    private UUID uid;

    @OneToMany(mappedBy = "parent", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    private Set<EntityB> setOfB;
}

@Entity
@Table(name = "Table_B")
public class EntityB {
   @Id
    @GeneratedValue(generator="uuid-generator")
    private UUID uid;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, optional = false)
    @JoinColumn(name = "parent_uid", referencedColumnName = "uid", nullable=false)
    private EntityA parent;
}

@ApplicationScoped
public class EntityARepository implements PanacheRepository<EntityA> {
}

I had to use the merge of the entity manager. As of today it is not available in a PanacheRepository

So I had to add in my repository:

public void merge(EntityA a) {
        getEntityManager().merge(a);
    }

Implementation ideas

I know it is only 2 lines of code but I would propose you to add to PanacheRepositoryBase

default void merge(Entity entity) {  
   JpaOperations.INSTANCE.merge(entity);
}
quarkus-bot[bot] commented 1 year ago

/cc @FroMage (panache), @loicmathieu (panache)

FroMage commented 1 year ago

IIRC we did not include merge by design, to avoid people using it too much and running into issues. Right, @Sanne ?

hakdogan commented 10 months ago

I thought it would be better to write it here rather than opening a new issue.

If we initially wrote some data to the database with a load script, the duplicate key value violates problem occurs with Panache because the Id is not defined explicitly.

If we define the Id explicitly, we get the exception detached entity passed to persist. I think this exception message in particular is quite confusing.

Can't the default Id provider mechanism obtain the next primary key value of the table before persisting the entity?