java - 扩展 CrudRepository,从一列中选择全部?

标签 java spring repository crud

我正在开发一个简单的 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/

相关文章:

java - 如何确定哪个类作为主类执行?

java - 如何从java中的HttpServletRequest中获取调用了哪个端点操作?

java - 在模块化 java 应用程序中配置 ehCache 的最佳实践

java - Maven 项目定义的存储库不起作用

java - 如何从源文件夹 eclipse 访问文件

java - Android:无法从用户存储读取文件

java - Spring捕获异常实现逻辑分支的案例有哪些?

java - 获取 javax.naming.NameNotFoundException : While starting tomcat

domain-driven-design - 领域驱动设计——层应该如何组织?

ios - Github API 返回发布数组的空 Assets