Hibernate HQL parameter bindings for queries

Source: Internet
Author: User

parameter bindings:
   Hibernatein the dynamic query parameter binding provides rich support, then what is the query parameter dynamic binding? In fact, if we're familiar with traditionJDBCprogramming, we are not difficult to understand the query parameters dynamic binding, the following code traditionJDBCparameter bindings for:
   preparestatement Pre=connection.prepare ("SELECT * from User where user.name=?");
   pre.setstring (1,"zhaoxin");
   ResultSet rs=pre.executequery ();
InHibernateA query parameter binding feature similar to this is provided in theHibernateThis feature also offers more than the traditionalJDBCoperations rich in many features, inHibernateThe CCP exists4type of parameter binding, we will describe the following separately:
A, by parameter name binding:   
InHQLyou define named parameters in the":"start with the following form:
   Query Query=session.createquery ("From user user where user.name=:customername anduser:customerage=:age ");
   query.setstring ("customername", name);
Query.setinteger ("customerage", age);   
In the code above: CustomerNameand the: Customeragenamed parameters are defined separatelyCustomerNameand theCustomerage, and then useQueryinterface ofsetxxx ()method to set the name parameter value,setxxx ()The method contains two parameters, namely the named parameter name and the actual value of the named parameter.
B, according to the parameter location bonding:   
InHQLIn query statements"?"to define the parameter position, in the following form:
   Query Query=session.createquery ("From user user where user.name=? and user.age =?   ");
  query.setstring (0,name);
Query.setinteger (1,age);  
Same usesetxxx ()method to set the binding parameters, but only thensetxxx ()the first parameter of the method represents the state parameter in theHQLthe position number that appears in the statement (by the0start numbering), the second parameter still represents the actual value of the parameter.
Note: In the actual development, the use of the name of the state named parameter, because this can not only provide a very good program readability, but also improve the ease of maintenance of the program, because when the location of the query parameter changes, the name of the state parameter is not necessary to adjust the program code.
C, setparameter () method:   
InHibernateof theHQLthe query can beSetparameter ()method states any type of parameter, as follows:
   String hql="From user user where user. name=:customername ";
  Query query=session.createquery (HQL);
   query.setparameter ("customername", name,hibernate.string);
As shown in the code above,Setparameter ()The method contains three parameters, named parameter names, actual values for named parameters, and named parameter mapping types. For some parameter typesSetparameter ()method can be based on the value of the parameterJavatype, guess the corresponding mapping type, so there is no need to display the mapping type, like the above example, can be written directly:
   query.setparameter ("customername", name); for some types, however, you must specify the type of mapping, such as java.util.Date type because it will correspond to the Hibernate A variety of mapping types , such asHibernate.dataorHibernate.timestamp.
   D, setproperties () Method : (setentity ())
  InHibernatecan be used insetproperties ()method to bind a named parameter to the property value of an object, as in the following program code:
   Customer customer=new customer ();
   customer.setname("Pansl");
   customer.setage(+);
   Query query=session.createquery (" From Customer C where c.name=:name and c.age=:age ");
   query.setproperties (customer);
   The setproperties () method automatically matches the property value of the Customer object instance to the named parameter, but requires that the named argument name must be The corresponding property of the entity object has the same name .
There's also a specialsetentity ()method, which relates the named parameter to a persisted object , as shown in the following code:
   Customer Customer= (customer) session.load (Customer.class, "1");
  Query Query=session.createquery ("From order order where Order.customer=:customer ");
   query. Setentity ("customer", customer);
  List list=query.list ();
The above code will generate a type similar to the followingSQLstatement:
   Select * from order where customer_id='1';
E, the advantages of using binding parameters:   
Why do we use binding named parameters? The existence of any thing has its value, specific to the binding parameters forHQLfor queries, there are two main advantages of the following:
   ①, you can use the database to implement performance optimizations becauseHibernateThe bottom-level use ispreparestatementto complete the query, so for different syntax parametersSQLstatement, you can take advantage of precompiledSQLstatement caching, which improves query efficiency.
   ②, can preventSQL Injectionthe emergence of security vulnerabilities:
   SQL Injectionis a special target forSQLstatements, such as for our common user login, in the login interface, the user input user name and password, the login validator may generate the followingHQLstatement:
   "From user user where user.name=' "+name+"'and user.password=' "+password+"'"
This oneHQLThere is no logical problem with the statement, this login verification function is normally done correctly, but if you enter it in the user name at logon"Zhaoxin or'x'='x",If you use a simpleHQLThe string of the statement is assembled, it generates the followingHQLstatement:
   "From user user where user.name='zhaoxin'or'x'='x'and user.password='Admin' ";
Apparently this oneHQLStatement ofwherewords will always be true, and the role of the user's password is meaningless, which isSQL Injectionthe basic principle of the attack.
Using the binding parameter method, the problem can be handled properly.,when binding parameters are used, the followingHQLstatement:
   From user user where user.name="'zhaoxin"' or 'x='x' and user.password=' admin'; This shows that using the binding parameter resolves the single quotation mark entered in the user name into a string (if you want to include single quotation marks in a string, you should use repeating single quotation marks), so parameter binding can effectively prevent SQL Injection security vulnerabilities.

Hibernate HQL parameter bindings for queries

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.