【问题标题】:Spring Data Repository for Entity where foreign key is also primary key外键也是主键的实体的 Spring 数据存储库
【发布时间】:2013-11-22 16:06:21
【问题描述】:

我在使用 JPA2 (EclipseLink) 和 Spring Data 1.4.2 时遇到了一些问题。 在我的情况下,两个表具有一对一的关系:

表A:

  • aId (PK)
  • ...

表B:

  • bId (PK, FK - 映射到 TableA 中的 aId)
  • ...

所以我尝试做这个实体:

实体A:

@Entity
@Table(name = "TableA")
public class EntityA implements Serializable {
    @Id
    @GeneratedValue
    @Column(name = "aId")
    private Long id;
    // another fields and getter/setter/business methods
    ... 
}

实体B:

@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> {
}

但对于实体B:

@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]. 

【问题讨论】:

  • 哪个类引发了异常?我认为问题出在EntityB中的OneToOne注解,那么EntityA中的id应该是EntityB类型。
  • 当容器尝试实例化 bRepository bean 时抛出异常。我只需要单向映射,所以我认为不需要反向链接。
  • 尝试将@MapsId 添加到EntityB 中的@OneToOne 注释:@OneToOne @MapsId
  • 引起:java.lang.NullPointerException at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.ObjectAccessor.processMapsId(ObjectAccessor.java:542) 我不知道为什么和它是怎么发生的:)

标签: java spring jpa foreign-key-relationship spring-data-jpa


【解决方案1】:

要使用的注解是@PrimaryKeyJoinColumn,而不是@JoinColumn

指定一个主键列,用作连接到另一个表的外键。

用于JOINED映射策略中实体子类的主表与其超类的主表的join;它在 SecondaryTable 注释中用于将辅助表连接到主表; 它可用于 OneToOne 映射,其中引用实体的主键用作被引用实体的外键

(强调我的)

【讨论】:

  • 谢谢。我之前尝试过使用这个注释,并看到了它的用法描述。但是使用此注释实例化 Spring Data 存储库也会引发异常 :( 也许问题在于我对 Spring Data 缺乏了解?
  • 好久没用这个注解了。 IIRC,您需要另一个 Long 类型的字段,用 @Id 注释。并且 ManyToOne 不应该用 @Id 注释。
  • @chepiov 为什么将其标记为答案,因为您报告 Spring 数据继续抛出异常?
【解决方案2】:

主要问题(例外)不是关于使用@JoinColumn 而不是@PrimaryKeyJoinColumn,而是当前 Spring Data 的限制(从 1.7.1 开始)。 我也遇到了这个问题并为此打开了DATAJPA-649。 我找不到解决方法,而是更改数据模型以使EntityB 具有独立于EntityA 的主键。使用@MapsId 也无济于事。

【讨论】:

    猜你喜欢
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多