我正在开发一个简单的 Spring 应用程序。尝试创建一个从 Crud 存储库扩展的接口(interface)。我在创建仅选择一列的方法时遇到问题。
我有一个“狗”模型。这是我的界面,其中包括一个应该选择我所有狗品种的方法:
public interface DogRepository extends CrudRepository<Dog, Long> {
@Query(value = "SELECT breed FROM dog", nativeQuery = true)
List<Dog> retrieveDogBreeds();
}
这给了我错误:
could not execute query; SQL [SELECT breed FROM dog]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query
我可以毫无问题地选择*:
@Query(value = "SELECT * FROM dog", nativeQuery = true)
^这会返回我 table 上的所有内容。
这是我的服务:
@Service
public class DogServiceImpl implements DogService{
@Autowired
DogRepository dogRepository;
public List<Dog> retrieveDogs() {
return (List<Dog>)dogRepository.findAll();
}
public List<Dog> retrieveDogBreeds(){
return (List<Dog>)dogRepository.retrieveDogBreeds();
}
}
这是我的 Controller :
@RestController
public class DogController {
private DogService dogService;
@Autowired
public void setDogService(DogService dogService) {
this.dogService = dogService;
}
@GetMapping("/dog")
public ResponseEntity<List<Dog>> getAllDogs() {
List<Dog> list = dogService.retrieveDogs();
return new ResponseEntity<List<Dog>>(list, HttpStatus.OK);
}
@GetMapping("/dog/breeds")
public ResponseEntity<List<Dog>> getAllBreeds() {
List<Dog> list = dogService.retrieveDogBreeds();
return new ResponseEntity<List<Dog>>(list, HttpStatus.OK);
}
}
我错过了什么?
最佳答案
通过更改语法解决了我的问题:
public interface DogRepository extends CrudRepository<Dog, Long> {
@Query("select d.breed from Dog d")
List<String> findAllBreed();
}
关于java - 扩展 CrudRepository,从一列中选择全部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57498751/