【发布时间】: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