我在@ManyToMany
关系中有两个实体,我希望通过它们的ID链接它们。
User
可以是许多Task
的经理,Task
可以有一个或多个经理,非常简单。
所以我用以下属性定义了我的实体:
@Entity
@Table(name = "task")
public class TaskEntity {
@Id
@Column(unique = true, name="task_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "user_task")
private Set<UserEntity> validators = new HashSet<>(0);
// Getters & setters
}
和
@Entity
@Table(name = "\"user\"")
public class UserEntity {
@Id
@Column(unique = true, name = "user_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "user_task")
private Set<TaskEntity> tasksToValidate = new HashSet<>(0);
// Getters & setters
}
Hibernate自动生成我的表格,由于某种原因,user_task
列有 4 列:UserEntity
的ID,经理的ID,{的ID {1}}以及要管理的任务的ID。但正如您所看到的,这些是相同值的对。
我如何告诉Hibernate我只想保留TaskEntity
的ID和UserEntity
的ID?
答案 0 :(得分:2)
你有双向的多对多关系。你必须将一方标记为父方,将另一方标记为子方。为此,您必须在父方使用mappedBy
。
请参阅此文章,了解使用多对多的最佳方式:https://vladmihalcea.com/the-best-way-to-use-the-manytomany-annotation-with-jpa-and-hibernate/