2015-07-21 129 views
0

我有一個NOTIFICATION表誰包含一個多對多的關聯:JPA多對多堅持

@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; 
} 

所以,我有一個關聯表稱爲PJ_PAR_NOTIF

我試圖堅持一個Notification實體。這裏是來自Value Object的piecesJointesGens初始化:

@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); 

堅持不起作用。 JPA爲我的通知對象的第一插入,這是確定:

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

然後,JPA嘗試在我的關聯表中插入值,但piecesJointesGen不存在的時刻:

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

所以,我有這樣的錯誤:

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

有沒有辦法告訴JPA的PJ_PAR_NOTIF插入之前,插入piecesJointesGen

+1

嘗試在'piecesJointesGens'映射中使用'@ManyToMany(cascade = CascadeType.PERSIST)'。 –

+0

這就是它!謝謝@PredragMaric! – user3469203

+0

太棒了,我已經添加了它作爲答案,因爲它幫助。 –

回答

1

修改piecesJointesGens映射到@ManyToMany(cascade = CascadeType.PERSIST)