扩展 CrudRepository,select 全部来自一列?

Extending CrudRepository, select all from one column?

我正在开发一个简单的 Spring 应用程序。尝试创建一个从 Crud Repository 扩展的接口。我在创建仅 select 一列的方法时遇到问题。

我有一个 'Dog' 模型。这是我的界面,其中包括一个应该 select 我所有犬种的方法:

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

我可以 select * 没问题:

    @Query(value = "SELECT * FROM dog", nativeQuery = true)

^returns 我的所有东西 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();
    }
}

这是我的控制器:

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

我错过了什么?

我建议尝试上面的 Dog Repository class 和 @Table 注释,因为您使用的是 SpringBoot。我不确定它是否有效,但我遇到了同样的异常问题 org.hibernate.exception.SQLGrammarException: could not execute query。所以,想分享

通过更改语法解决了我的问题:

public interface DogRepository extends CrudRepository<Dog, Long> {
    @Query("select d.breed from Dog d")
    List<String> findAllBreed();
}