Difference between using @OneToMany and @ManyToMany

前端 未结 3 1348
陌清茗
陌清茗 2020-12-28 20:01

I am having some trouble understanding the difference between @OneToMany and @ManyToMany. When I use @OneToMany it defaults to create

3条回答
  •  醉酒成梦
    2020-12-28 20:20

    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;
        ...
    }
    

提交回复
热议问题