我有一个实体,它有一个 JPA 2.x 定义的主键,也是一个外键 到另一个实体(JPA 2.x 允许在@*ToOne
关系字段上@Id
注释(:
@Entity
class FooOptionalInfo {
/* ... fields ... */
@Id
@OneToOne
public Foo getFoo() { return foo; }
/* ... setters ... */
}
@Entity
class Foo {
@Id
public Long fooId;
/* ... getters/setters ... */
}
Spring JPA 存储库接口应该扩展Repository<T, ID>
接口,其中T
是@Entity
类,ID
是实体的@Id
字段,但是:
定义public interface FooOptionalInfoRepository extends Repository<Foo, Bar>
或extends Repository<FooOptionalInfo, Long>
会导致在 Spring jpa 初始化时出现以下相同的错误:
Caused by: java.lang.IllegalArgumentException: This class [class com.example.FooOptionalInfo] does not define an IdClass
at org.hibernate.jpa.internal.metamodel.AbstractIdentifiableType.getIdClassAttributes(AbstractIdentifiableType.java:183)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation$IdMetadata.<init>(JpaMetamodelEntityInformation.java:253)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:84)
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:68)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:153)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:100)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:82)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:199)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
... 20 common frames omitted
我是否需要恢复到 JPA 1.x 标准并定义实体和基本 id 字段(@Id Long fooId; @OneToOne @PrimaryKeyJoinColumn(...) Foo foo;
FooOptionalInfo
(,或者有没有办法吃 JPA 2.x 简化注释并拥有我的弹簧存储库蛋糕?
id
同时是主键和外键是一个奇怪的问题。您可以通过另一种方式完成此操作:在Bar
中定义外键。
@Entity
class Foo {
@Id
private long id;
// ...
}
@Entity
class Bar {
@Id
public Long barId;
@OneToOne
@JoinColumn(name="foo_id")
private Foo foo;
}