简体   繁体   English

有没有办法使用 jdbc 在 spring 启动应用程序中开发动态 sql 查询?

[英]Is there a way to develop dynamic sql query in spring boot app with jdbc?

I am developing backend for a webapp in Spring Boot using Spring Data JDBC with MYSQL(phpmyadmin) database.我正在使用 Spring 数据 JDBC 和 MYSQL(phpmyadmin) 数据库在 Spring 引导中为 webapp 开发后端。 The problem is, there is a table ClientInfo with more than 12 columns.问题是,有一个超过 12 列的表 ClientInfo。 Client may query the backend by any number of parameters(columns in database).客户端可以通过任意数量的参数(数据库中的列)查询后端。 Should I write controller and sql query for every condition provided by client or is there better way to appraoch to solve this problem.我应该为客户提供的每个条件编写 controller 和 sql 查询,还是有更好的方法来解决这个问题。

Edited: Actually I am not using ORM.编辑:实际上我没有使用 ORM。 I am using JDBC and JDBI.我正在使用 JDBC 和 JDBI。

You can use Spring Data JPA Query by Example.您可以使用 Spring 数据 JPA 查询示例。 Depending on what the client provides, you build an org.springframework.data.domain.Example and then you use it in the query:根据客户端提供的内容,您构建一个org.springframework.data.domain.Example ,然后在查询中使用它:

ClientInfo c = new ClientInfo();
c.setFirstName("Bill");
Example<ClientInfo> example = Example.of(c);    
List<ClientInfo> results = clientInfoRepository.findAll(example);

In this case the ClientInfoRepository needs to extend JpaRepository:在这种情况下,ClientInfoRepository 需要扩展 JpaRepository:

public interface ClientInfoRepository extends JpaRepository<ClientInfo, Long> {}

For the sql query part: 12 columns are not a lot.对于 sql 查询部分:12列不是很多。 You probably can use handy OR-mapping (JPA/hibernate) to retrieve the result into a ClientInfo object at the backend.您可能可以使用方便的 OR-mapping (JPA/hibernate) 将结果检索到后端的 ClientInfo object 中。

For the controller part: from my understanding you're returning selected-fields in resulted data sending back to a web client based on certain request parameters.对于 controller 部分:据我了解,您将根据某些请求参数将结果数据中的选定字段返回给 web 客户端。 Suppose you're returning a json result using a spring web controller, you probably can also only create a single controller. Suppose you're returning a json result using a spring web controller, you probably can also only create a single controller. And then control what to be included in the replied json.然后控制要包含在回复的 json 中的内容。 Applying simple technique/logic should be able to achieve this - for example if you use jackson for json handling you may set all the fields you don't want to include as null, and then use @JsonInclude NON_NULL annotations to exclude them.应用简单的技术/逻辑应该能够实现这一点 - 例如,如果您使用 jackson 进行 json 处理,您可以将所有不想包含的字段设置为 Z37A6259CC0C1DAE299A7866489DFFON_BDZ 以排除它们,然后包含它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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