简体   繁体   中英

How to get the specific fields by API Spring Boot

I need to REST the request by the GET to transfer to the parameters of the field that I want to get from the database sql (from hibernate)

@GetMapping("/product")
public Object getProducts(@RequestParam(name = "fields") String fields) {
   // how?
}



@Repository
public interface ProductRuRepository extends JpaRepository<Product, Long> {
@Query("SELECT ?1 FROM Product p")
List<Product> findByFields(String fields);
}

I'm waiting to get the fields that I passed to the parameter. But the project does not compile

Please change your code to this structure:

Associate product repository to your rest controller.

   @RestController
   class ProductController {

    ProductRuRepository productRepository;

    @GetMapping("/product")
    public List<Product> getProducts(@RequestParam(name = "fields") String fields) 
    {
    List<Product> productList = productRepository.findByFields(fields);
    return productList;  
    }

    }

Your repository will trigger runtime exception because of syntax issue in JPA Query.

Change the query as mentioned below.

@Query(value = "SELECT :fields FROM Product as p")
List<Product> findByFields(String fields);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM