欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jpa实体关系-一对多

程序员文章站 2022-04-23 15:51:44
...

jpa实体关系-一对多

双向一对多映射

如一个Department中有多个Employeem,而一对多的关系往往是双向的

@Entity
public class Employeem {


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private String name;

    @ManyToOne
    @JoinColumn(name = "dept_id")  //关系拥有者,在employeem表中有dept_id字段
    private Department department;
    //getter & setter omit..
}


@Entity
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private String departName;

    //mappedBy指向关系拥有者中的Department属性
    @OneToMany(mappedBy = "department", fetch = FetchType.EAGER)
    private List<Employeem> employeems;
}

生成的表结构:

mysql> desc department;
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| id          | int(11)      | NO   | PRI | NULL    |       |
| depart_name | varchar(255) | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
2 rows in set

mysql> desc employeem;
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| id      | int(11)      | NO   | PRI | NULL    |       |
| name    | varchar(255) | YES  |     | NULL    |       |
| dept_id | int(11)      | YES  | MUL | NULL    |       |
+---------+--------------+------+-----+---------+-------+
3 rows in set

当定义双向一对多(或者多对一)的时候,两个重要点:

  • 多对一方是关系所有方,所以在那一方定义联接列(@JoinColumn)
  • 一对多方是反方,所以必须使用mappedBy元素