【发布时间】:2020-03-03 23:35:35
【问题描述】:
我有两个实体 Foo 和 Bar 处于多对多关系中。加入实体是FooBar,由于这个实体有另一个属性(它自己的id),我在所有者端(FooBar)使用@ManyToOne,在依赖实体(Foo和Bar)中使用@OneToMany )。如何创建一个FooBarRepository 扩展CrudRepository 而没有FooBar 内的显式复合键字段?理想情况下,我不想更改 FooBar 类的成员。
我尝试使用@IdClass,但我不想在FooBar 中包含fooId 和barId 字段,我得到了这个异常:
Caused by: org.hibernate.AnnotationException: Property of @IdClass not found in entity com.nano.testers.test.FooBar: barId
我也尝试遵循IdClass 的文档并明确地按名称引用列,但我失败了(也许解决方案就在这里?)
主键类中的字段或属性的名称与实体的主键字段或属性的名称必须对应,并且它们的类型必须相同。
我尝试将Foo 和Bar 中的字段名称更改为仅id,以便它们在连接表中被引用为foo_id 和bar_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