之前用的 mybatis,各种查询都是自己写,非常快捷
最近开始练习使用 jpa
涉及到多表关联,用起来有点头痛
我写了一个 demo,涉及 3 张表,学生,老师,学生-老师关联表
Student
@Entity
@Table
@Data
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 32)
private String name;
@JoinTable(name = "student_and_teacher",
joinColumns = {@JoinColumn(name = "studentId", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "teacherId", referencedColumnName = "id")},
foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT),
inverseForeignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT))
@ManyToMany
private List<Teacher> teachers;
}
其中的 @JoinTable 就是表明要关联到学生-老师关联表中去
Teacher 类
@Entity
@Table
@Data
public class Teacher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 32)
private String name;
}
然后就是学生-老师关联
student-teacher
@Entity
@Table(name = "teacher_and_lesson")
@Data
public class StudentAndTeacher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private Long studentId;
@Column
private Long teacherId;
}
这一套工作的很好,可以查询出学生-老师关系,添加一些数据后,执行查询学生的方法,可以得到
{"id":1,"name":"Joe","teachers":[{"id":1,"name":"王老师"},{"id":2,"name":"李老师"}]}
但是,这个时候,我想增加一个 课程表,设定每个老师教一个课程
Lesson
@Entity
@Table
@Data
public class Lesson {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 32)
private String name;
}
然后,就是增加老师-课程关联关系
TeacherAndLesson
@Entity
@Table
@Data
public class TeacherAndLesson {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private Long lessonId;
@Column
private Long teacherId;
}
这样的话,就需要在老师实体类中,增加一个课程的关联关系
@Entity
@Table
@Data
public class Teacher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 32)
private String name;
@JoinTable(name = "teacher_and_lesson",
joinColumns = {@JoinColumn(name = "teacherId", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "lessonId", referencedColumnName = "id")},
foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT),
inverseForeignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT))
@OneToOne
private Lesson lesson;
}
这样写了之后,程序启动完成,自动创建的 teacher_and_lesson 表中,会多出一个 student_id 出来,
没搞懂是为啥。😭
求大佬指点,谢谢。。。
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.