我有一个JPA 2.x定义主键的实体,它也是另一个实体的外键(对于 @*ToOne
关系字段的 @Id
注释,JPA 2.x allows):
@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
字段,但是:
在spring jpa初始化时,定义 public interface FooOptionalInfoRepository extends Repository<Foo, Bar>
或 extends Repository<FooOptionalInfo, Long>
会产生相同的错误:
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
Do I need to revert back to JPA 1.x standards and define both the Entity and the basic id field (@Id Long fooId; @OneToOne @PrimaryKeyJoinColumn(...) Foo foo; in FooOptionalInfo) or is there a way to eat the JPA 2.x simplified annotations and have my spring repository cake as well?
1 回答
对于
id
同时成为主键和外键来说,这是一个奇怪的垃圾 . 您可以通过另一种方式完成此操作:在Bar
中定义外键 .