동적으로 SQL을 생성하고 준비된 문을 사용할 수 있습니다.
이것이 어떻게 수행 될 수 있는지 생각해보십시오.
StringBuilder whereClause = new StringBuilder();
if (name != null) {
whereClause.append(String.format("name = '%s'", name));
}
// other similar conditions
String sql = "select * from table" + (whereClause.length() != 0 ? "where " + whereClause.toString() : "");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
// use rs to fetch data
그리고 당신은 다음과 같아야합니다
StringBuilder whereClause = new StringBuilder();
ArrayList<Object> parameters = new ArrayList<>();
if (name != null) {
whereClause.append("name = ?");
parameters.add(name);
}
// other similar conditions
String sql = "select * from table" + (whereClause.length() != 0 ? "where " + whereClause.toString() : "");
PreparedStatement stmt = connection.prepareStatement();
for (int i = 0; i < parameters.length(); ++i) {
setParameterValue(stmt, i + 1, parameter.get(i));
}
ResultSet rs = stmt.executeQuery(sql);
// use rs to fetch data
setParameterValue
처럼 뭔가로 변경해야합니다 : 지금 당신은 다음과 같은 코드를 MyBatis로와
void setParameterValue(PreparedStatement ps, int index, Object value) {
if (value instanceof String) {
ps.setString(index, (String)value);
} if (value instanceof Integer) {
ps.setInt(index, (Integer)value);
} // and more boilerplate code like this for all types you need
}
당신 can 피하기 쓰기 이러한 보일러 플레이트 코드는 동적 SQL을 생성하고이를 훨씬 쉽게 만듭니다. 그러나 CSA가 mybatis가 SQL을 처리하는 방법을 알지 못합니다.
코드가 인젝션 증거인 것으로 확인되면 동적 값을 "검증"할 수있는 방법이 없습니다. 쿼리를 매개 변수화해야합니다. –
여러 질문을하고 있는데 SCA 도구에 대한 질문은 내가 한 번도 해본 적이없는 단서를 가지고있다. 동적 SQL 제거에 대한 질문은 더 많은 정보가 필요합니다. 동적 SQL은 무엇을합니까? 마지막으로 QUOTENAME을 사용하여 소싱 입력을 어느 정도 수행 할 수 있습니다. 이것이 충분하지 않으면 모든 신체 구멍에서 나올 때까지 중첩 된 대체물로 불쾌한 udf를 만들 수 있습니다. – Tristan
나는 팀을 위해 SQL에 대한 훈련을 받기를 제안한다. 이를 처리하는 가장 좋은 방법은 저장 프로 시저입니다. 그리고 그것은 약간의 분리를 제공합니다. 모든 SQL이 코드 내에 포함되어 있다면 추상화 레이어를 작성하여 코드가 더 쉽게 작업 할 수 있도록해야합니다. –