加载没有关系的单个实体jpa

htrmnn0y  于 2021-07-22  发布在  Java
关注(0)|答案(1)|浏览(253)

我有两个实体的学生和成绩。它们之间存在一对多的关系。但是当我调用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=?
kokeuurv

kokeuurv1#

要仅加载学生实体,可以创建一个单独的投影,如 StudenDTO 并使用它通过repo服务控制器。
投影的相关部分在这里

interface StudentDTO {
    String getName();

    String getLastname();

    Integer getAge();

    String getEmail();
}

现在当你击中 localhost:8080/students/create-dto-return?id=1 您不会看到下一个查询被触发,这是在序列化过程中触发的。
整个代码如下:

package com.example.demo;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;

@RestController
@RequestMapping("/students")
public class StudentsController {

    private final StudentService studentService;

    @Autowired
    public StudentsController(StudentService studentService) {
        this.studentService = studentService;
    }

    @GetMapping
    public Iterable<Student> list() {
        return studentService.list();
    }

    @PostMapping
    public Student createEntityReturn(@RequestBody Student student) {
        return studentService.save(student);
    }

    @GetMapping(value = "/create-dto-return")
    public StudentDTO getByDto(@RequestParam("id") Integer id) {
        return studentService.findStudentOnlyByIdDto(id);
    }

    @GetMapping(value = "/create-entity-return")
    public Student getById(@RequestParam("id") Integer id) {
        return studentService.findStudentById(id);
    }

}

@Getter
@Setter
@ToString
@Entity
class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer 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<>();

}

@Getter
@Setter
@Entity
@Table
class Grade {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String subject;

    private double value;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "student_id", nullable = false)
    private Student student;
}

@Service
class StudentService {
    private final StudentRepository studentRepository;

    @Autowired
    StudentService(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    @Transactional
    public Student save(Student student) {
        return studentRepository.save(student);
    }

    @Transactional(readOnly = true)
    public Iterable<Student> list() {
        return studentRepository.findAll();
    }

    @Transactional(readOnly = true)
    public StudentDTO findStudentOnlyByIdDto(Integer id) {
        return studentRepository.findStudentById(id);
    }

    @Transactional(readOnly = true)
    public Student findStudentById(Integer id) {
        return studentRepository.findById(id).orElseThrow(() -> new RuntimeException("Unable to find student"));
    }
}

interface StudentDTO {
    String getName();

    String getLastname();

    Integer getAge();

    String getEmail();
}

@Repository
interface StudentRepository extends JpaRepository<Student, Integer> {
    StudentDTO findStudentById(Integer id);
}

相关问题