![](/img/trans.png)
[英]Defining a spring-data JPA repository interface for entity with primary key that is also a foreign key in JPA 2.x
[英]Spring Data Repository for Entity where foreign key is also primary key
我在使用JPA2(EclipseLink)和Spring Data 1.4.2時遇到了一些問題。 在我的例子中,兩個表具有一對一的關系:
表A:
表B:
所以我試着做這個實體:
EntityA:
@Entity
@Table(name = "TableA")
public class EntityA implements Serializable {
@Id
@GeneratedValue
@Column(name = "aId")
private Long id;
// another fields and getter/setter/business methods
...
}
EntityB:
@Entity
@Table(name = "TableB")
public class EntityB {
@Id
@OneToOne
@JoinColumn(name = "bId", referencedColumnName = "aId")
private EntityA id;
// another fields and getter/setter/business methods
...
}
EntityA的Spring Data Repository運行良好:
@Repository(value = "aRepository")
public interface RepositoryA extends CrudRepository<EntityA, Long> {
}
但對於EntityB:
@Repository(value = "bRepository")
public interface RepositoryB extends PagingAndSortingRepository<EntityB, EntityA> {
}
拋出異常:
Expected id attribute type [class java.lang.Long] on the existing id attribute [SingularAttributeImpl[EntityTypeImpl@5270829:EntityA [....] but found attribute type [class EntityB].
主要問題(例外)與@JoinColumn
而不是@PrimaryKeyJoinColumn
的使用@PrimaryKeyJoinColumn
,但必須是當前Spring數據的限制(截至1.7.1)。 我也遇到了這個問題並為它打開了DATAJPA-649 。 我找不到解決方法,而不是更改數據模型,以便EntityB
具有獨立於EntityA
的主鍵。 使用@MapsId
也無濟於事。
要使用的注釋是@PrimaryKeyJoinColumn
,而不是@JoinColumn
:
指定用作連接到另一個表的外鍵的主鍵列。
它用於將JOINED映射策略中實體子類的主表連接到其超類的主表; 它在SecondaryTable注釋中用於將輔助表連接到主表; 它可以用在OneToOne映射中,其中引用實體的主鍵用作引用實體的外鍵 。
(強調我的)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.