gpt4 book ai didi

java - Spring JPA - 方法 "getById"不工作,我得到 null

转载 作者:行者123 更新时间:2023-12-05 01:27:03 24 4
gpt4 key购买 nike

我试图通过 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() {
}

这是方法,

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

}

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

Repository 是标准的仓库,扩展了JPA

最佳答案

您必须使用返回 Optional 的 findById

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

来自文档:

Returns a reference to the entity with the given identifier. Dependingon how the JPA persistence provider is implemented this is very likelyto always return an instance and throw an EntityNotFoundException onfirst access. Some of them will reject invalid identifiersimmediately.

所以一直是proxy可能没有初始化导致问题

关于java - Spring JPA - 方法 "getById"不工作,我得到 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69813532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com