简体   繁体   中英

Hibernate @ManyToMany has 2 unnecessary columns

I have two entities on a @ManyToMany relationship where I wish to link them by their ID.

A User can be the manager of many Task s and a Task can have one or many managers, pretty simple.

So I defined my entities with the following attributes:

@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    
}

And

@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 automatically generates my table, and for some reason user_task has 4 columns: the ID of the UserEntity , the ID of the manager, the ID of the TaskEntity and the ID of the task to be managed. But as you can see, these are pairs of the same values.

How may I tell Hibernate that I only wish to keep the ID of the UserEntity and the ID of the TaskEntity ?

You have bidirectional many-to-many relations. You have to mark one side as a parent side and the other as a child side. To do this you have to use mappedBy on the parent side.

Refer to this article about best way to use many-to-many: https://vladmihalcea.com/the-best-way-to-use-the-manytomany-annotation-with-jpa-and-hibernate/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM