zoukankan      html  css  js  c++  java
  • jpa关联映射(一)

    开发中常用到数据表的关联(其实很难遇到。。),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;





  • 相关阅读:
    Sort it
    set 集合容器
    convertToString与ToString的区别
    string基本字符系列容器
    辗转相除法
    进程的总结
    进程池进阶
    进程池
    生产者消费者模型
    IPC :进程之间的通信
  • 原文地址:https://www.cnblogs.com/JAYIT/p/8566267.html
Copyright © 2011-2022 走看看