using precompiled SQL statements and placeholder parameters (in JDBC) can avoid the complexity of using string concatenation of SQL statements. Let's start with a simple look at the benefits of using precompiled SQL statements. Use String sql = "SELECT * from Student where name=" + name; If the value of name is 1 or "aty" or "Aty ' Aty", the following error will be generated for SQL
--ora-01722 Invalid Numberselect * from student where name=1;--ora-00904 invalid Identifierselect * from student where Nam e=aty;--ora-01756:quoted string not properly terminatedselect * from student where Name=aty ' aty;
In the construction of SQL, so that if the string concatenation, you must consider the data type, whether the need to add single quotation marks and other details, a little attention, will result in an error SQL statement. When stitching strings a lot, the code is almost unreadable, and locating the problem is very difficult. This is the advantage of precompiled SQL in code readability and simplicity. There is also the performance advantage, can refer to my another blog: hql or SQL use? Benefits: Reduce SQL parsing time, reduce memory overhead, prevent SQL injection.
JDBC provides preparedstatement.setxxx () to replace the placeholder parameters, and hibernate corresponds to Setparameter and setparameterlist.
The difference between setparameter and setparameterlist is that when using 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);
Obviously, it's easier to use setparameterlist code. This is also a compliment to the API design of Hibernate, which provides the usual cumbersome practices setparameter and provides a simple and easy-to-use setparameterlist. This consistency provides more options for people who are familiar with and unfamiliar with hibernate.
Hibernate Setparameter and setparameterlist in precompiled SQL statements