Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't Hibernate generate primary key for many-to-many relationship table?

I have a simple many-to-many tables. One Term can belong to multiple Categories, and one Category can be assigned to multiple Terms.

Term.java

@Entity
public class Term implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @NotNull
    @Size(min = 1, max = 100)
    private String name;

    @ManyToMany(mappedBy="terms")
    private List<Category> categories = new ArrayList<Category>();

    ...
    // getters and setters
}

Category.java

@Entity
public class Category implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @NotNull
    @Size(min = 1, max = 255)
    private String name;

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    private List<Term> terms = new ArrayList<>();

   // getters and setters
}

However, the generated intersection table "" doesn't contain a primary key, as seen from here:

MariaDB [wordDS]>describe Category_Term;
+---------------+------------+------+-----+---------+-------+
| Field         | Type       | Null | Key | Default | Extra |
+---------------+------------+------+-----+---------+-------+
| categories_id | bigint(20) | NO   | MUL | NULL    |       |
| terms_id      | bigint(20) | NO   | MUL | NULL    |       |
+---------------+------------+------+-----+---------+-------+

Shouldn't a Composite Key always be needed as a primary key, and should automatically created by Hibernate? How can I get that created automatically?

like image 380
user697911 Avatar asked Feb 07 '23 10:02

user697911


1 Answers

Use a Set instead of a List to enforce uniqueness. Hibernate will generate the primary key.

@ManyToMany(mappedBy="terms")
private Set<Category> categories = new HashSet<Category>();

/* ... */

@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private Set<Term> terms = new HashSet<>();
like image 124
Robby Cornelissen Avatar answered Feb 13 '23 04:02

Robby Cornelissen