Home > Back-end >  Spring JPA - method "getById" is not working, I get null
Spring JPA - method "getById" is not working, I get null

Time:11-03

I am trying to get object by ID, but I can't figure it out , why i get null and it isn`t working..

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

And here is the method,

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

}

After exercise line on debug mode i get this " {ExerciseEntity$HibernateProxy$B...}" I think it can be possibly from relationship, but everything seems fine to me. Any help would be appreciate

Repository is standard repository, extending JPA

CodePudding user response:

You must use findById that returns an Optional.

getById returns not an entity but a reference.

From the documentation:

Returns a reference to the entity with the given identifier. Depending on how the JPA persistence provider is implemented this is very likely to always return an instance and throw an EntityNotFoundException on first access. Some of them will reject invalid identifiers immediately.

So it's always a proxy that may not be initialized and causes the problem

  • Related