Spring JPA - 方法“getById”不起作用,我得到 null

Geo*_*zov 3 java spring jpa spring-data-jpa

我试图通过 ID 获取对象,但我无法弄清楚为什么我得到 null 并且它不起作用..

@Entity
@Table(name = "exercises")
public class ExerciseEntity {

@Id
private Long id;
private String nameOfExercise;
private Integer caloriesBurnedForHour;
@Column(columnDefinition = "TEXT")
private String bonusInfo;
@ManyToMany(mappedBy = "exerciseEntityList",fetch = FetchType.EAGER)
private List<PersonalTrainingProgram> personalTrainingPrograms;

public ExerciseEntity() {
}


@Entity
public class PersonalTrainingProgram {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany
@JoinTable()
private List<ExerciseEntity> exerciseEntityList;
@ManyToOne
private FoodProgram foodProgram;
@ManyToOne
private AppUser appUser;

public PersonalTrainingProgram() {
}
Run Code Online (Sandbox Code Playgroud)

这是方法,

@Override
public List<ExerciseEntity> findExercisesBySpecificId(List<ExerciseDto> exerciseDto) {

    List<ExerciseEntity> listEntity= new ArrayList<>();
    for (int i = 0; i <exerciseDto.size() ; i++) {
        ExerciseEntity byId = exercisesRepository.getById(exerciseDto.get(i).getId());
        listEntity.add(byId);
    }
    return listEntity;
}

@Override
public void addItToDatabase(List<ExerciseDto> exerciseDto, FoodProgramDto 
foodProgramDto,String username) {
 PersonalTrainingProgram personalTrainingProgram = new PersonalTrainingProgram();
 personalTrainingProgram.setExerciseEntityList(findExercisesBySpecificId(exerciseDto));
 personalTrainingProgram.setFoodProgram(foodProgramService
.findFoodProgramById(foodProgramDto));
 personalTrainingProgram.setAppUser(appUserRepository.findByUsername(username).get());
personalTrainingRepository.save(personalTrainingProgram);

}
Run Code Online (Sandbox Code Playgroud)

在调试模式下进行练习后,我得到这个“ {ExerciseEntity$HibernateProxy$B...}” 我认为这可能来自关系,但对我来说一切似乎都很好。任何帮助将不胜感激

Repository是标准存储库,扩展了JPA

Sim*_*lli 7

您必须使用findById它返回一个Optional。

getById 返回的不是实体而是引用。

从文档中:

返回对具有给定标识符的实体的引用。根据 JPA 持久性提供程序的实现方式,这很可能始终返回一个实例并在第一次访问时抛出 EntityNotFoundException。其中一些会立即拒绝无效标识符。

所以它始终是一个可能未初始化的代理并导致问题