从PreparedStatement
开始,似乎参数化SQL语句只允许开发人员使用?
和PreparedStatement.setX(index, value)
来指定位置参数:
PreparedStatement statement = connection.prepareStatement("select * from something where id = ?;");
statement.setString(1, '5');
有没有办法为这样的预处理语句提供命名参数:
ParameterizedStatement statement = connection.parameterizeStatement(
"select * from something where id = $id;");
statement.setString("id", "5");
在Java中是否存在某种东西?
答案 0 :(得分:2)
不在基础JDK中,但这听起来像MyBatis SQL Builder类。
例如,
// Anonymous inner class
public String deletePersonSql() {
return new SQL() {{
DELETE_FROM("USER");
WHERE("ID = ${id}");
}}.toString();
}
// Builder / Fluent style
public String insertPersonSql() {
String sql = new SQL()
.INSERT_INTO("USER");
.VALUES("ID, FIRST_NAME", "${id}, ${firstName}")
.VALUES("LAST_NAME", "${lastName}")
.toString();
return sql;
}
答案 1 :(得分:1)
JPA查询可以使用命名参数,例如:
EntityManager em = ...
Query q = em.createQuery("SELECT x FROM Magazine x WHERE x.title = :titleParam and x.price > :priceParam");
q.setParameter("titleParam", "JDJ");
q.setParameter("priceParam", 5.0);
List<Magazine> results = (List<Magazine>) q.getResultList();