java – 实体的Spring Data Repository,其中外键也是主键

我在使用JPA2(EclipseLink)和Spring Data 1.4.2时遇到了一些问题.
在我的例子中,两个表具有一对一的关系:

表A:

> aId(PK)
> ……

表B:

> bId(PK,FK – 映射到TableA中的aId)
> ……

所以我试着做这个实体:

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]. 
最佳答案
要使用的注释是@PrimaryKeyJoinColumn,而不是@JoinColumn:

Specifies a primary key column that is used as a foreign key to join to another table.

It is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity.

(强调我的)

转载注明原文:java – 实体的Spring Data Repository,其中外键也是主键 - 代码日志