这是我第一次使用spring和Dto,我试图创建两个,classes和student,我的问题是当我试图发送一个classes的get请求时,通常响应需要是与这个classe相关的name,numberS averageC和student,但我得到的是这个{“name”:“phonexe”,“numberS”:25,“averageC”:0.0,“学生”:null }学生列表总是空的,我在数据库中检查学生是否插入了classe_id,所以这不是问题这是我的实体
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String codeM;
private String firstName;
private String lastName;
@ManyToOne
@JoinColumn(name = "classes_id")
private Classes classes;
@OneToMany(mappedBy = "student")
private List<Notes> notes;
}
@Entity
@Data
@NoArgsConstructor(force = true)
@AllArgsConstructor
public class Classes {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
@NonNull
@NotBlank(message = "First name must be filled")
@Pattern(regexp = "^(?!\\s*$).+", message = "First name must not be blank or contain only spaces")
private String name;
@NonNull
private Integer numberS;
private double averageC=0.0;
@OneToMany
private List<Student> student;
}
这是我的Dto实体
@Data
public class StudentGetDto {
@NotNull
private String codeM;
private String firstName;
private String lastName;
private ClassesGetDto classes;
private List<NotesGetWithMatiereOnlyDto> notes;
}
@Data
public class ClassesGetDto {
private String name;
private Integer numberS;
private Double averageC;
private List<StudentGetDto> students;
}
这是控制器的功能
@GetMapping("/{Name}")
public ClassesGetDto findByName(@PathVariable String Name) throws Exception{
return modelMapper.map(classesService.findByName(Name), ClassesGetDto.class);
}
modelMapper配置
@Configuration
public class ModelMapperConfig {
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}
2条答案
按热度按时间mxg2im7a1#
如果你确信你没有前面提到的延迟加载问题,你可以检查循环引用:如果实体之间存在循环引用,则在序列化到DTO期间可能会导致问题。确保实体之间没有循环依赖关系,因为这可能导致无限递归或意外结果。您可以使用@JsonIgnore或@JsonManagedReference和@JsonBackReference等注解在序列化期间正确处理循环引用。
ss2ws0br2#
@OneToMany()
默认提取类型为Lazy。尝试使用FetchType.EAGER
。示例: