JPA 问题(延迟加载?急切?)

时间:2021-05-08 16:08:32

标签: spring spring-boot hibernate

我正在构建一个简单的 Spring Boot 应用程序,包含 2 个实体:

- Student model

    @Entity
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Student {
     @Id @GeneratedValue(strategy = GenerationType.IDENTITY)    
     private Long id;
     private String name;
     private String password;
     private boolean active;
     private Date dob;
     private String roles;
     @ManyToOne
     private Training training;
    }

- Training model

    @Entity
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Training {
      @Id @GeneratedValue(strategy = GenerationType.IDENTITY)   
      private Long id;
      private String name;
      private int duration;
      @OneToMany(mappedBy = "training")
      @JsonIgnore
      private Collection<Student> students;
    }

编辑

我通过在数据库中添加 2 个资源来运行应用程序:

    public static void main(String[] args) {
        SpringApplication.run(MsSchoolingSbApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        
        Training t1=trainingRepo.save(new Training(null,"php", 20, null));
        Training t2=trainingRepo.save(new Training(null,"java", 20, null));
        Student st=new Student(null, "XXXX", "ZZZZ", true,new Date(),"ADMIN",t1);
        Student st2=new Student(null, "XXXXX2", "ZZZZZ2", true,new Date(),"USER",t2);
        studentRepo.save(st);
        studentRepo.save(st2);
    }

结束编辑

编辑 2

- StudentRepo
@RepositoryRestController
public interface StudentRepo extends JpaRepository<Student, Long>{

    public List<Student> findByNameStartsWith(String name);
    
    Optional<Student> findByName(String name);
}

- TrainingRepo
  @RepositoryRestController
    public interface TrainingRepo extends JpaRepository<Training, Long> {
    
    }

结束编辑 2

我试过把 fetch = FetchType.EAGERLAZY,我也加了 @JsonIgnore 但只要我用新数据(培训和学生)填充数据库并运行应用程序,我收到此消息:

Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.schooling.models.Training.students, could not initialize proxy - no Session

我做错了什么?

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

不要在@Entity 类上使用 Lombok 的 @Data 注释。

原因:@Data 生成使用生成的 getter 的 hashcode()、equals() 和 toString() 方法。使用 getter 当然意味着获取新数据,即使该属性被标记为 FetchType=LAZY。

在 Hibernate 的某个地方尝试使用 toString() 记录数据但它崩溃了

编辑 您可以通过添加从 toString 方法中排除关系,例如在我的情况下: @ToString(exclude = {"students"})