我正在尝试使用 Spring boot 构建简单的博客应用程序。但是,现在当我尝试将 findOne 用于 service.java 时,我遇到了“The method findOne(Long) is undefined for the type PersonRepository”的问题。以下是我所做的
我尝试在存储库中创建对象来指示 findOne 并保存。但是它没有帮助
PersonRepository.java
package PersonRepository.javaio.javabrains.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import io.javabrains.Entity.Person;
@Repository
public interface PersonRepository extends CrudRepository<Person,Long>{
public Person findByEmail(String email);
/*
* public Person findOne(Long id);
*
* public Iterable<Person> findAll();
*
* public Person save(Person person);
*/
PersonService.java
@Service
public class PersonService {
@Autowired
private PersonRepository personRepository;
public Object findAll(){
return personRepository.findAll();
}
public Person findById(Long id){
return personRepository.findOne(id);
}
我预计消除评论 block 可以解决问题。但是,当我尝试运行该应用程序时,它显示错误
最佳答案
最好使用JpaRepository
(它扩展了CRUD存储库)
您可以使用 getOne()
或 findById 代替
(可选)findOne()
()
findById()
Retrieves an entity by its id.
Parameters:id must not be null.
Returns:the entity with the given id or Optional#empty() if none found
Throws:IllegalArgumentException - if id is null.
getOne()
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 javax.persistence.EntityNotFoundException on first access. Some of them will reject invalid identifiersimmediately.
Parameters:id must not be null.
Returns:a reference to the entity with the given identifier.
关于java - PersonRepository 类型的 findOne(Long) 方法未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57184276/