使用主键定义实体的spring-data JPA存储库接口,主键也是JPA 2.x中的外键

时间:2017-07-07 01:45:43

标签: java spring-data-jpa jpa-2.0

我有一个带有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简化注释并拥有我的弹簧库蛋糕?

1 个答案:

答案 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;
}