我有這個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設計。
親切的問候 馬西莫