JPA关系映射之one-to-many和many-to-one

Posted SaraMorning

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JPA关系映射之one-to-many和many-to-one相关的知识,希望对你有一定的参考价值。

one-to-many(一对多)和many-to-one(多对一)双向关联

假设教师与学生是一对多关系,反过来学生与教师就是多对一关系。

1、Teacher.java

 1 public class Teacher {  
 2     private long id;  
 3     private String teaName;  
 4     private Set<Student> students = new HashSet<Student>();  
 5     public long getId() {  
 6         return id;  
 7     }  
 8     public void setId(long id) {  
 9         this.id = id;  
10     }  
11     public String getTeaName() {  
12         return teaName;  
13     }  
14     public void setTeaName(String teaName) {  
15         this.teaName = teaName;  
16     }  
17       
18     public Set getStudents() {  
19         return students;  
20     }  
21     public void setStudents(Set students) {  
22         this.students = students;  
23     }  
24     public String toString() {  
25         return "Teacher:[teacherId=" + this.id + "/tteacherName="  
26                 + this.teaName + "]";  
27     }  
28 } 

Student.java

 1 public class Student {
 2     private long id;
 3     private String stuName;
 4     private Teacher teacher;
 5 
 6     public long getId() {
 7         return id;
 8     }
 9 
10     public void setId(long id) {
11         this.id = id;
12     }
13 
14     public String getStuName() {
15         return stuName;
16     }
17 
18     public void setStuName(String stuName) {
19         this.stuName = stuName;
20     }
21 
22     public Teacher getTeacher() {
23         return teacher;
24     }
25 
26     public void setTeacher(Teacher teacher) {
27         this.teacher = teacher;
28     }
29 
30     public String toString() {
31         return "student:[studentId=" + this.id + "/tstudentName="
32                 + this.stuName + "]";
33     }
34 }

 

 

sdfd

以上是关于JPA关系映射之one-to-many和many-to-one的主要内容,如果未能解决你的问题,请参考以下文章

使用注解的Hibernate one-to-many映射

Hibernate关系映射之many-to-many(多对多)

Hibernate基于注解的双向one-to-many映射关系的实现

Hibernate初探之一对多映射 继续学习

spring-data-jpa——如果使用了one-to-many,many-to-one的注解,在Jackson进行json字符串化时出现错误的解决方案

Hibernate双向多对多对象关系模型映射