Home > Back-end >  SpringBoot findById method in repository not working
SpringBoot findById method in repository not working

Time:06-05

Error Message I am trying to make a simple SpringBoot application and get this error when trying to run it. Not sure why.

@Service
public class UserService {

    @Autowired
    UserRepository userRepository;

    public User getUserByEmail(String email) {
        return userRepository.findByEmail(email);
    }


    public User createUser(User u) {
        User user = userRepository.save(u);
        return user;
    }

    public void deleteUserById(Long id) {
        userRepository.deleteById(id);
    }

    public User findUserById(Long id) {
        return userRepository.findById(id);
    }
}

Here is a link to the repository as well: https://github.com/deckard20202020/HelpingHand

CodePudding user response:

I think I just need to add <Optional on the return type.

CodePudding user response:

JpaRepository

JpaRepository already implements many frequently used signatures. One of them is <T> findById(Integer id); which clashes with your signature containing a Long as parameter for id.

You don't have to add the signature, you can already use it out of the box.

Since I saw you were doubting what what abstraction to use, here is the order of abstraction hierarchy:

  • Repository
  • CrudRepository
  • PagingAndSortingRepository
  • JpaRepository
  • You can also make your own abstraction

Your own abstraction

public interface SomeJpaRepository extends SomeRepositry, CrudRepositry<Some, Long> {
    // Extra functionality on top of the provided CRUD
}

public interface SomeRepository {
    // Implemented methods and helpers to be used by the service
}

Sidenote: You also don't need to add the @Repository annotation, because Spring Data already scans the classpath for any interface or class that is of type JpaRepository.

CodePudding user response:

Welcome to stackoverflow, @deckard2020!

I think you need to use @Transactional(readonly = true) decoration for findUserById function in UserService.

  • Related