我有一个带有JPA 2.x定义主键的实体,它也是一个外键
到另一个实体(@Id
关系字段上的@*ToOne
注释的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
我是否需要恢复到JPA 1.x标准并定义实体和基本ID字段(@Id Long fooId; @OneToOne @PrimaryKeyJoinColumn(...) Foo foo;
中的FooOptionalInfo
)或者有没有办法吃JPA 2.x简化注释并拥有我的弹簧库蛋糕?
答案 0 :(得分:0)
id
同时成为主键和外键是一个奇怪的垃圾。您可以通过另一种方式完成此操作:在Bar
。
@Entity
class Foo {
@Id
private long id;
// ...
}
@Entity
class Bar {
@Id
public Long barId;
@OneToOne
@JoinColumn(name="foo_id")
private Foo foo;
}