2011-03-16 81 views
1

我有這個ER模型JPA問題的一個一對一的關聯級聯= PERSIST

Message 0..1 <--> 0..1 MessageDetail 
    PK:ID_MESSAGE   PK: ID_DETAIL 
     NAME     DETAIL 
          FK: ID_MESSAGE 

,相對對象的映射是:

class OnlineEventMessage { 
    @Id 
    @Column(name = "ID_EVENT_MESSAGE") 
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ") 
    private Long idEventMessage; 

    @OneToOne(mappedBy="onlineEventMessage", cascade=CascadeType.PERSIST) 
    private EventMessageAnagrafica eventMessageAnagrafica; 
} 

public class EventMessageAnagrafica { 

    @Id 
    @Column(name = "ID_EVENT_MESSAGE_ANAG") 
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ") 
    private Long idEventMessageAnagrafica; 

    @OneToOne(cascade=CascadeType.PERSIST) 
    @JoinColumn(name = "FK_ID_EVENT_MESSAGE") 
    private OnlineEventMessage<?> onlineEventMessage; 
} 

這個測試表明我是多麼想處理對象:

@Test 
    public void testSaveItem() { 
     EntityManager entityManager = factoryCont0.createEntityManager(); 

     entityManager.getTransaction().begin(); 

     OnlineEventMessage<String> eventMessage = new OnlineEventMessage<String>(EventType.ONLINE_REIMPIANTO_CONTRATTO); 

     EventMessageAnagrafica eventMessageAnagrafica = new EventMessageAnagrafica(multichannelId); 
     eventMessage.setEventMessageAnagrafica(eventMessageAnagrafica); 

     entityManager.persist(eventMessage); 
     entityManager.getTransaction().commit(); 
     entityManager.close(); 
    } 

當我堅持在eventMessageAnagrafica的事件消息不保存FK。 兩種方法來節省墊層關聯有:

1)添加這行代碼:eventMessageAnagrafica.setOnlineEventMessage(eventMessage); 並保存該子對象:entityManager.persist(eventMessageAnagrafica);

2)改變爲下面的父設定器:

public void setEventMessageAnagrafica(EventMessageAnagrafica eventMessageAnagrafica) { 
     this.eventMessageAnagrafica = eventMessageAnagrafica; 
     if (eventMessageAnagrafica != null) { 
      eventMessageAnagrafica.setOnlineEventMessage(this); 
     } 
    } 

有沒有其他乾淨的方法來完成這個? P.S.最初FK在父表的Message上,但DBA告訴我這不是一個好的ER設計。

親切的問候 馬西莫

回答

2

保持在內存中的對象之間的雙向關係,雙方之間的一致性是你的責任。在保存關係時,JPA提供程序查看關係的擁有方,即在沒有mappedBy的那一方。

我認爲第二種方法是最乾淨的,因爲它自動保持一致性,所以你不能忘記去做。或者,您可以創建一個特殊函數來關聯除setter之外的這些實體,並限制對setter的訪問。

0
entityManager.getTransaction().begin(); 

OnlineEventMessage<String> eventMessage = new OnlineEventMessage<String>(EventType.ONLINE_REIMPIANTO_CONTRATTO); 

EventMessageAnagrafica eventMessageAnagrafica = new EventMessageAnagrafica(multichannelId); 
eventMessage.setEventMessageAnagrafica(eventMessageAnagrafica); 

//add this line 
eventMessageAnagrafica.setEventMessage(eventMessage); 

entityManager.persist(eventMessage);