我使用了Spring MVC,如何对Mysql进行动态查询?我的控制器中有类似的东西:public String getNewsByDateAndAuthor(Model model, HttpServletRequest request) {}
如何使用 URL 中的所有参数request.getParameterMap()
,而我的地图将<String, List<String>>
使用它创建动态查询?
例如,如果我有 3 个参数,我想生成一个这样的查询:
SELECT * FROM news WHERE parameter = IN(val1, val2...) AND parameter2 = IN(val1, val2...) AND parameter3 = IN(val1, val2...)
或类似的东西是我只有一个参数;
SELECT * FROM news WHERE parameter = IN(val1, val2...)
如果有人知道,请告诉我如何做到这一点。
我想要一些这样的代码:
public String getQuery(Map<String,List<String>> parameters){
List<String> author = new ArrayList<>();
List<String> startDate = new ArrayList<>();
List<String> endDate = new ArrayList<>();
List<String> categories = new ArrayList<>();
List<String> about = new ArrayList<>();
List<String> soureID = new ArrayList<>();
if (!parameters.get("author").isEmpty())
for (int i = 0; i < parameters.get("author").size(); i++) {
author.add(parameters.get("author").get(i));
}
if (!parameters.get("startDate").isEmpty())
for (int i = 0; i < parameters.get("startDate").size(); i++) {
startDate.add(parameters.get("startDate").get(i));
}
if (!parameters.get("endDate").isEmpty())
for (int i = 0; i < parameters.get("endDate").size(); i++) {
endDate.add(parameters.get("endDate").get(i));
}
if (!parameters.get("categories").isEmpty())
for (int i = 0; i < parameters.get("categories").size(); i++) {
categories.add(parameters.get("categories").get(i));
}
if (!parameters.get("about").isEmpty())
for (int i = 0; i < parameters.get("about").size(); i++) {
about.add(parameters.get("about").get(i));
}
if (!parameters.get("soureID").isEmpty())
for (int i = 0; i < parameters.get("soureID").size(); i++) {
soureID.add(parameters.get("soureID").get(i));
}
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append("SELECT * FROM news WHERE");
if (!author.isEmpty()) {
String authors = author.toString();
authors.replace(" ", " , ");
queryBuilder.append(" author = IN ( " + authors + " ) AND");
}
if (!startDate.isEmpty()) {
String startDates = startDate.toString();
startDates.replace(" ", " , ");
queryBuilder.append(" author = IN ( " + startDates + " ) AND");
}
if (!endDate.isEmpty()) {
String endDates = endDate.toString();
endDates.replace(" ", " , ");
queryBuilder.append(" author = IN ( " + endDates + " ) AND");
}
if (!categories.isEmpty()) {
String categoriesR = categories.toString();
categoriesR.replace(" ", " , ");
queryBuilder.append(" author = IN ( " + categoriesR + " ) AND");
}
if (!about.isEmpty()) {
String abouts = about.toString();
abouts.replace(" ", " , ");
queryBuilder.append(" author = IN ( " + abouts + " ) AND");
}
if (!soureID.isEmpty()) {
String sourceIDs = soureID.toString();
sourceIDs.replace(" ", " , ");
queryBuilder.append(" author = IN ( " + sourceIDs + " ) AND");
}
queryBuilder.delete(queryBuilder.length() - 3, queryBuilder.length());
String query = queryBuilder.toString();
return query;
}