Problem when wanting to update JPA

0

I'm using Java with JPA and I have a festival entity and another festival edition. A festival can have many editions. The question that when I release an edition, after doing em.persist, I have to do

   res.getFestival().getFestivalEdicions().add(res);

   em.merge(res.getFestival());

Is there any way to make jpa aware of the changes and update?

The full method of the create is:

 @Override
@MethodName(name = MethodsNameAgam.FESTIVALEDICION_ADD)
public FestivalEdicion create(FestivalEdicionTran tran) throws Exception {
    assign(tran, Op.CREATE);
    validate(tran, Op.CREATE);
    FestivalEdicion res = tran.build(Op.CREATE);

    if (tran.getPortada() != null && tran.getPortada().isSet()) {
        Contenido portada = contenidoCont.create(tran.getPortada());
        res.setPortada(portada);
    }

    em.persist(res);

    //AGREGAR A LA LSITA DE EDCIONES DEL FESTIVAL, LA EDICIONE CREADA
    res.getFestival().getFestivalEdicions().add(res);

    em.merge(res.getFestival());

    return res;
}
    
asked by Juan Pablo B 28.09.2018 в 17:04
source

1 answer

0

Yes, with waterfalls. I imagine that the association between Festival and Edition is something like this:

@Entity
class Festival {
  @OneToMany(mappedBy = "festival", cascade = ALL)
  List<Edicion> ediciones;
}

The cascade = ALL attribute causes all operations applied to Festival to propagate to Edit. If you also want to remove an edition of the list from the database, you can do:

@OneToMany(mappedBy = "festival", cascade = ALL, orphanRemoval=true)

It is also possible not to propagate all operations but only some. For more information read this article: Hibernate JPA cascade types .

By the way, if the addition of Edition to Festival occurs in the same transaction in which you saved (persist) the festival, it is not necessary to incorporate (merge) the changes again, because the EntityManager is already monitoring additional changes from that you save it.

    
answered by 28.09.2018 в 20:03