码迷,mamicode.com
首页 > 其他好文 > 详细

jpa关联映射(一)

时间:2018-03-14 12:54:38      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:img   for   也会   数据   主题   注解   orm   -o   生成   

开发中常用到数据表的关联(其实很难遇到。。),spring-data-jpa(其实是hibernate)提供了一整套十分方便的注解来供我们使用表关联功能。

OneToOne
OneToMany
ManyToOne
ManyToMany

举例之前,先理解两个表的关系中,哪一个是主体,一对一以及多对多需要自己按照现实场景来区分,而一对多和多对一始终是以多的一方为主体的。注解在使用中“始终在非主体的一方标记自己在主体中的名称”。
理解上面一段话,那么操作也会变得很简单。
开始前,把我们之前测试的Student表的主键生成策略改成自增,需要新增一些实体,ER图如下:

 
技术分享图片

一对一

Student和Score是一对一的关系,Score类如下:

@Entity
@Table(name = "score")
public class Score {

  @Id
  @GeneratedValue
  private Integer id;

  @Column(name = "chinese_score")
  private Integer chinese;

  @Column(name = "math_score")
  private Integer math;

//省略get/set
}

现在开始建立它和Student的关系,首先在Student类中加入元素Score,在Score类中也加入元素Student,并都用OneToOne标注,你中有我,我中有你。
Score:

  @OneToOne
  private Student student;

Student:

  @OneToOne
  private Score score;

然后我们需要区分谁是主体,按照现实理解,肯定是Student,于是我们需要在非主体的那个类中标注出它在主体中的名字,也就是在Score类中标注它在Student类中的名字:

  @OneToOne(mappedBy = "score")
  private Student student;


此外,我们还可以设置映射级联,只需要在注解中增加参数(千万要注意必须在主体一侧):

  @OneToOne(cascade = CascadeType.REMOVE )
  private Score score;

当student删除的时候,score对应也会删除。其他可以参看CascadeType类。

一对多(多对一)

现在我们开始建立student和school的关系,根据我们开始说的,student肯定是主体,那么我们只需要在school中标注出它在student中的名称就好了。建立School类:

@Entity
@Table(name = "school")
public class School {

  @Id
  @GeneratedValue
  private Integer id;

  private String name;

//省略get/set
}

在Student类中加入School,并且指定关系是多对一

  @ManyToOne
  private School school;

在School中建立Student集合,指定关系是一对多,并且申明它在Student类中的名称

  @OneToMany(mappedBy = "school")
  private List<Student> students;

多对多

看到现在,大概也能知道多对多怎么设置了,我们新建Subject

@Entity
@Table(name = "subject")
public class Subject {

  @Id
  @GeneratedValue
  private Integer id;

  @Column(length = 10)
  private String name;

//省略get/set
}
分析可以知道,Student仍然是关系的主题,所以我们需要在Subject类中标注它在Student类中的名称。

Student:

  @ManyToMany
  private List<Subject> subjects;

Subject:

  @ManyToMany(mappedBy = "subjects")
  private List<Student> students;





jpa关联映射(一)

标签:img   for   也会   数据   主题   注解   orm   -o   生成   

原文地址:https://www.cnblogs.com/JAYIT/p/8566267.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!