【问题标题】:Spring and JPA 2.0 - Composite key in many to many relationship with extra columnSpring 和 JPA 2.0 - 与额外列的多对多关系中的复合键
【发布时间】:2020-03-03 23:35:35
【问题描述】:

我有两个实体 Foo 和 Bar 处于多对多关系中。加入实体是FooBar,由于这个实体有另一个属性(它自己的id),我在所有者端(FooBar)使用@ManyToOne,在依赖实体(FooBar)中使用@OneToMany )。如何创建一个FooBarRepository 扩展CrudRepository 而没有FooBar 内的显式复合键字段?理想情况下,我不想更改 FooBar 类的成员。

我尝试使用@IdClass,但我不想在FooBar 中包含fooIdbarId 字段,我得到了这个异常:

Caused by: org.hibernate.AnnotationException: Property of @IdClass not found in entity com.nano.testers.test.FooBar: barId

我也尝试遵循IdClass 的文档并明确地按名称引用列,但我失败了(也许解决方案就在这里?)

主键类中的字段或属性的名称与实体的主键字段或属性的名称必须对应,并且它们的类型必须相同。

我尝试将FooBar 中的字段名称更改为仅id,以便它们在连接表中被引用为foo_idbar_id,但例外情况相同.

我不想使用@EmbeddedId,如果这意味着我需要在FooBar 类中包含FooBarPk 类型的字段。

@Entity
public class Foo {
    @Id
    private Long fooId;

    @OneToMany(mappedBy = "foo", cascade = CascadeType.ALL)
    private Set<FooBar> foobars;
}
@Entity
public class Bar {
    @Id
    private Long barId;

    @OneToMany(mappedBy = "bar", cascade = CascadeType.ALL)
    private Set<FooBar> foobars;
}
@Entity
//@IdClass(FooBarPk.class)
public class FooBar implements Serializable {
    @Id
    private Long fooBarId;

    @Id
    @ManyToOne
    @JoinColumn
    private Foo foo;

    @Id
    @ManyToOne
    @JoinColumn
    private Bar bar;

}
public class FooBarPk implements Serializable {
    private Long fooId;
    private Long barId;
    private Long fooBarId;
}
public interface FooBarRepository extends CrudRepository<FooBar, FooBarPk> {
}

【问题讨论】:

    标签: java spring jpa spring-data many-to-many


    【解决方案1】:

    看起来复合键类中的字段名称必须与引用实体的名称相同。我认为这些名称不符合简洁代码原则,但我现在必须接受这个解决方案。

    public class FooBarPk implements Serializable {
        private Long foo;
        private Long bar;
        private Long fooBarId;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-07
      • 2015-12-13
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多