多的一方:不写任何关联关系

package com.eneitys;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name="tb_student")
public class Student {
   
    private int id;
    private String stuName;
   
    @Id
    @GeneratedValue
    public int getId() {
       return id;
    }
    public void setId(int id) {
       this.id = id;
    }
    public String getStuName() {
       return stuName;
    }
    public void setStuName(String stuName) {
       this.stuName = stuName;
    }
}

 

 

 

 

一的一方:添加多的一方的Set集合

 

package com.eneitys;
 
import java.util.HashSet;
import java.util.Set;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
 
@Entity
@Table(name="tb_group")
public class Group {
   
    private int id;
    private String grpName;
   
    private Set<Student> set=new HashSet<Student>();
   
    @Id
    @GeneratedValue
    public int getId() {
       return id;
    }
    public void setId(int id) {
       this.id = id;
    }
    public String getGrpName() {
       return grpName;
    }
    public void setGrpName(String grpName) {
       this.grpName = grpName;
    }
   
    @OneToMany
    @JoinColumn(name="group_id")
    public Set<Student> getSet() {
       return set;
    }
    public void setSet(Set<Student> set) {
       this.set = set;
    }
}

 

 

总结:

@OneToMany在默认情况下,Hibernate会把一对多当成多对多的一种特殊情况!结果就是会帮我们生成一张中间表,所以注意要写@JoinColumn(name="")注解,因为在数据库中,不管是一对多还是多对一,都是在多的一方添加一的一个外键,所以这个jioncolumn的name值一般写成一的外键字段名