我有两个实体的学生和成绩。它们之间存在一对多的关系。但是当我调用api来获得学生时,我得到了他们所有的分数。有没有办法只载入学生实体?我试过了,但没用。
学生模型:
@Entity
@Table
public class Student {
@Id
@GeneratedValue(
strategy= GenerationType.AUTO,
generator="native"
)
@GenericGenerator(
name = "native",
strategy = "native"
)
private Long id;
@NotBlank(message = "Name cannot be null")
private String name;
@NotBlank(message = "Lastname cannot be null")
private String lastname;
@NotNull(message = "Age cannot be null")
private int age;
@NotBlank(message = "Email cannot be null")
private String email;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "student")
private Set<Grade> grades = new HashSet();
}
等级型号:
@Entity
@Table
public class Grade {
@Id
@GeneratedValue(
strategy= GenerationType.AUTO,
generator="native"
)
@GenericGenerator(
name = "native",
strategy = "native"
)
private Long id;
private String subject;
private double value;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "student_id", nullable = false)
private Student student;
学生服务:
@Service
public class StudentService {
private final IStudentRepository studentRepository;
public StudentService(IStudentRepository studentRepository){
this.studentRepository = studentRepository;
}
public List<Student> GetAll(){
return studentRepository.findAll();
}
休眠输出:
Hibernate: select student0_.id as id1_1_, student0_.age as age2_1_, student0_.email as email3_1_, student0_.lastname as lastname4_1_, student0_.name as name5_1_ from student student0_
Hibernate: select grades0_.student_id as student_4_0_0_, grades0_.id as id1_0_0_, grades0_.id as id1_0_1_, grades0_.student_id as student_4_0_1_, grades0_.subject as subject2_0_1_, grades0_.value as value3_0_1_ from grade grades0_ where grades0_.student_id=?
1条答案
按热度按时间kokeuurv1#
要仅加载学生实体,可以创建一个单独的投影,如
StudenDTO
并使用它通过repo服务控制器。投影的相关部分在这里
现在当你击中
localhost:8080/students/create-dto-return?id=1
您不会看到下一个查询被触发,这是在序列化过程中触发的。整个代码如下: