hibernate预编译SQL语句中的setParameter和setParameterList,hibernate预编译
使用预编译SQL语句和占位符参数(在jdbc中是?),能够避免因为使用字符串拼接sql语句带来的复杂性。我们先来简单的看下,使用预编译SQL语句的好处。使用String sql = "select * from Student where name=" + name;如果name的值是1或 "aty"或"aty'aty",就会产生下面错误的sql
--ORA-01722 invalid number select * from student where name=1; --ORA-00904 invalid identifier select * from student where name=aty; --ORA-01756: quoted string not properly terminated select * from student where name=aty'aty;
在构造sql的时候,使如果用了字符串拼接,就必须考虑数据类型,是否需要加单引号等细节问题,稍微不注意,就会导致错误sql语句。当拼接字符串很多的时候,代码几乎不可读,定位问题也十分困难。这是预编译sql在代码可读性和简单性上的优势。还有就是性能上的优势,可以参考我的另一篇博文:HQL或SQL使用?带来的好处:减少SQL解析时间、降低内存开销、防止SQL注入。
JDBC提供PreparedStatement.setXXX()来替换占位参数,hibernate对应的是setParameter和setParameterList。
setParameter和setParameterList的区别在于,使用in的时候。
Object[] params = new Integer[]{1, 2};
String hqlF = "from Student where id in (?,?)";
Query query = session.createQuery(hqlF);
for (int i = 0; i < params.length; i++)
{
query.setParameter(i, params[i]);
}
//String hqlS = "from Student where id in :valueList";
String hqlS = "from Student where id in (:valueList)";
Query queryS = session.createQuery(hqlS);
queryS.setParameterList("valueList", params);
很显然,使用setParameterList代码更简单。这里也赞美下hibernate的API设计,既提供了常规繁琐的做法setParameter,也提供了简洁易用的setParameterList。这种一致性,对于熟悉和不熟悉hibernate的人来说,提供了更多的选择。
设置你的查询参数用的。
比如 "from Customer o where o.name=?1"
setParameter(1,"java");
=====================
可以,但不建议,因为你得注意SQL注入等问题。
select * Topic as model where model.boardId=? limit 1,6 不是赋值的问题。而是你的hql语句错误。这里边没有from关键字。你要查哪个表的映射?