如何在 Spring Boot 中使用 MySql 数据库查询? [英] How to use MySql Database queries in Spring Boot?
问题描述
我正在使用 Spring Boot 创建 API.在这个项目中,我使用了 spring web、JPA、jstl 和 MySql 作为 API 的依赖项.在这个项目中,我创建了一个控制器、模型和存储库.基本上,此 API 执行 CRUD 操作.当我使用 GET 请求时,我只想获取 3 列.但是,情况是我在这里使用了 JPA,但我不知道如何使用像
I am creating an API by using spring boot. In this project, I used spring web, JPA, jstl and MySql as dependencies of the API. In this project, I have created a Controller, Model and Repository. Basically, this API does CRUD operations. When I use GET request, I want to get only 3 columns. But, the case is I used JPA in this and I don't know how to use custom queries like
"SELECT devname,hrs,ot FROM imaginaryTable"
"SELECT devname,hrs,ot FROM imaginaryTable"
.
我该怎么做??
我的控制器类.
@RestController
@RequestMapping("/api")
public class ImController {
@Autowired
private ImRepository TaskRepository;
@GetMapping("/projects")
public List<ImModel> findAll() {
return (List<ImModel>) TaskRepository.findAll();
}
@GetMapping("/developers/{id}")
public ImModel findByName(@PathVariable final int id){
return TaskRepository.findById(id);
}
}
我的存储库界面.
package com.kisalka.pacrestapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.kisalka.pacrestapi.model.ImModel;
public interface ImRepository extends JpaRepository<ImModel, Integer> {
ImModel findById(int id);
}
推荐答案
您可以在存储库中使用 @Query("Your query")
注释来查询数据库.例如
You could use @Query("Your query")
annotation inside the repository to query the database.
For Example
@Query(value="SELECT devname,hrs,ot FROM imaginaryTable",nativeQuery=true)
private List<Object> getValues();
希望它能解决您的问题.
Hope it solves your issue.
这篇关于如何在 Spring Boot 中使用 MySql 数据库查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!