简体   繁体   English

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

[英]Load single entity without relations jpa

I have two entities students and grades.我有两个实体的学生和成绩。 There is a one to many relationship between them.它们之间是一对多的关系。 But when I make an api call to get students, I get all grades with them.但是,当我拨打 api 电话以获取学生时,我会与他们一起获得所有成绩。 Is there a way to load only student entity?有没有办法只加载学生实体? I tried FetchType.LAZY but it did not work.我试过 FetchType.LAZY 但它没有用。

Student model:学生 model:

@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();
}

Grade model:牌号 model:

@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;

Student service:学生服务:

@Service
public class StudentService {

private final IStudentRepository studentRepository;

public StudentService(IStudentRepository studentRepository){
    this.studentRepository = studentRepository;
}

public List<Student> GetAll(){
    return studentRepository.findAll();
}

Hibernate output: Hibernate output:

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=?

To load only the student entity, you can create a separate projection like StudenDTO and use it to pass across repo-service-controller.要仅加载学生实体,您可以创建一个单独的投影,如StudenDTO并使用它来传递 repo-service-controller。

The relevant part of projection is here投影的相关部分在这里

interface StudentDTO {
    String getName();

    String getLastname();

    Integer getAge();

    String getEmail();
}

Now when you hit localhost:8080/students/create-dto-return?id=1现在当你点击localhost:8080/students/create-dto-return?id=1

You won't see the next query being fired and this is triggered jackson during serialization.您不会看到下一个查询被触发,这是在序列化期间触发的 jackson。

Entire code is as below:整个代码如下:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM