JPA ManyToMany persist

主宰稳场 提交于 2019-12-14 03:07:20

问题


I have a NOTIFICATION table who contains one ManyToMany association :

@Entity
@Table(name="NOTIFICATION")
@NamedQuery(name="Notification.findAll", query="SELECT f FROM Notification f")
public class Notification {

/** SOME COLUMN DEFINITION NOT IMPORTANT FOR MY CASE
    COD, DATE, ID_THEME, ID_TYP, IC_ARCH, ID_CLIENT, INFOS, NAME, TITRE_NOT, ID_NOT
**/

        @ManyToMany
        @JoinTable(
            name="PJ_PAR_NOTIF"
            , joinColumns={
                @JoinColumn(name="ID_NOTIF")
                }
            , inverseJoinColumns={
                @JoinColumn(name="ID_PJ_GEN")
                }
            )
        private List<PiecesJointesGen> piecesJointesGens;
}

So, I have an association table called PJ_PAR_NOTIF.

I try to persist a Notification entity. Here is piecesJointesGens initialisation, from a Value Object :

@PersistenceContext(unitName="pu/middle")

private EntityManager entityMgr;

FoaNotification lFoaNotification = new FoaNotification();

for(PieceJointeGenVO lPJGenVO : pNotificationVO.getPiecesJointes()){
        PiecesJointesGen lPiecesJointesGen = new PiecesJointesGen();
        lPiecesJointesGen.setLienPjGen(lPJGenVO.getLienPieceJointeGen());
        lPiecesJointesGen.setIdPjGen(lPJGenVO.getIdPieceJointeGen());
        lNotification.getFoaPiecesJointesGens().add(lFoaPiecesJointesGen);
}

entityMgr.persist(pNotification);

The persist doesn't work. JPA generate a first insert for my Notification object, that is ok :

insert 
into
    NOTIFICATION
    (COD, DATE, ID_THEME, ID_TYP, IC_ARCH, ID_CLIENT, INFOS, NAME, TITRE_NOT, ID_NOT) 
values
    (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

Then, JPA try to insert values in my association table, but piecesJointesGen doesn't exists for the moment :

insert 
into
    PJ_PAR_NOTIF
    (ID_NOTIF, ID_PJ_GEN) 
values
    (?, ?)

So, I have this error :

GRAVE: EJB Exception: : java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.entities.PiecesJointesGen

Is there a way to tell JPA to insert piecesJointesGen before the PJ_PAR_NOTIF insert ?


回答1:


Modify piecesJointesGens mapping to @ManyToMany(cascade = CascadeType.PERSIST).



来源:https://stackoverflow.com/questions/31534871/jpa-manytomany-persist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!