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?
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<>();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With