1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| package io.kid1999.teacher_manager.model;
import lombok.Data; import javax.persistence.*; import java.util.List;
@Data @Entity @Table public class Student { @Id private Integer studentId; private String studentName;
/** * 多对一 ManyToOne * JPA中,many一端作为维护端,One一端作为被维护端 * many一方指定@ManyToOne注解 ,并使用 @JoinClomn指定关联的外键 */
private Integer gradeId; @ManyToOne(targetEntity = Grade.class,fetch = FetchType.LAZY) //对应的对象,且设置为懒加载(不在每一次查询时都进行多表关联) @JoinColumn(name = "gradeId",insertable = false,updatable = false) //对应关联的键,在插入更新时不插入grade private Grade grade;
/** * 多对多的维护端 需要一个中间表进行维护 */ @ManyToMany @JoinTable(name = "students_roles", // 指定中间表名 joinColumns ={@JoinColumn(name = "studentId",referencedColumnName = "studentId")}, // 指定中间表和student的关联 inverseJoinColumns = {@JoinColumn(name = "roleId",referencedColumnName = "roleId")} // 指定中间表和role的关联 ) private List<Role> roles;
// 必须重新toString 不然在打印时候会递归查询 grade @Override public String toString() { return "Student{" + "studentId=" + studentId + ", studentName='" + studentName + '\'' + ", gradeId=" + gradeId + '}'; } }
|