[英]Many-to-one unidirectional relation in DataNucleus
對於上下文,客戶端我使用MVP模式,因此具有One
列表的視圖只知道ID,當我在服務器上收到新的Many
時,我希望能夠只更新One
的外鍵,使用“setOneId”或空的One
對象,其ID設置為所需值。
所以我嘗試在DataNucleus中創建一個多對一的單向,我有點掙扎。 我可以使用JDO或JPA,我真的不在乎。 在JPA中,我試過這個:
@Entity
public class Many {
@Id
String id;
@ManyToOne
@Join(name = "idOne")
One one;
}
@Entity
public class One {
@Id
String id;
}
這幾乎就是我想要的。 創建了一對多,但使用了連接表。 我希望有一個直接的關系。 當我插入/更新一個Many
,我不想插入/更新相關的One
,只需在我的Many
對象中使用好的id更新idOne
。
我找到了這個博文 ,但它是Hibernate,我認為它仍然使用連接表:
@Entity
public class Many {
@Id
public String id;
@Column(name="idOne")
private String idOne;
@ManyToOne
@JoinColumn(name="idOne", nullable=false, insertable=false, updatable=false)
private One one;
}
我試過了,但我得到了這個錯誤 。
我不明白我是如何與之斗爭的。 我的目標是有保留一些參考數據(比如作為類國家的名單表One
),以及(如鎮為類“工作項目”列表Many
,我沒有創建/更新創建/更新)引用數據,只是它在Many
對象中的外鍵。
如果它是單向關聯,並且Many
是擁有方(根據你的第二個例子),你正走向錯誤的方向。 委托更新並在單向關系的擁有方插入責任沒有多大意義(與insertable = false和updateable = false一樣)。
編輯:更新的答案所以你想要的是多對一,擁有一個外鍵列。 嘗試這個
@Entity
public class Many {
@Id
String id;
@ManyToOne
@JoinColumn(name = "foreignKeyColumn")
One one;
}
@Entity
public class A {
@Id
String id;
@OneToOne(cascade=CascadeType.ALL)
B b;
}
@Entity
public class B {
@Id
String id;
}
如果你將初始對象保持為
tx.begin();
A a = new A("FirstA");
B b1 = new B("FirstB");
B b2 = new B("SecondB");
a.setB(b1);
em.persist(a);
em.persist(b2);
tx.commit();
... (some time later)
tx.begin();
A a = em.find(A.class, "FirstA");
B b2 = em.getReference(B.class, "SecondB");
// update the B in A to the second one
a.setB(b2);
tx.commit();
這會更新A和B之間的FK。不能簡單
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.