I am having some trouble understanding the difference between @OneToMany and @ManyToMany. When I use @OneToMany it defaults to create
In your Questions & Categories case, you should use @ManyToMany relationship. @ManyToMany basically means that "a Question can belong to many Categories at the same time" and "a Category can contain many Questions at the same time". A new table will automatically be created to store the mappings. Your code would look like this:
@Entity
public class Question implements Serializable {
...
@ManyToMany
private List categories;
...
}
@Entity
public class Category implements Serializable {
...
@ManyToMany
private List questions;
...
}
If you use @OneToMany relationship for your Questions and Categories (let's say Category on the One side and Questions on the other), this means that "a Question can only belong to one Category" and "a Category can contain many Questions at the same time". No new table is needed to store the mapping. Instead, a new field will automatically be created in the Many side to record the ID of the One side. Your code would look like this:
@Entity
public class Question implements Serializable {
...
@ManyToOne
private Category theCategory;
...
}
@Entity
public class Category implements Serializable {
...
@OneToMany(mappedBy="theCategory")
private List questions;
...
}