Several schemes to prevent SQL injection in the use of Hibernate

  • 2021-12-04 19:24:46
  • OfStack

Several schemes to prevent SQL injection in the use of Hibernate

Hibernate is an open source object-relational mapping framework, which encapsulates JDBC with very lightweight objects, so that Java programmers can manipulate databases with object programming thinking at will.

While obtaining convenient operation, the injection problem of SQL also deserves our close attention. Let's talk about some ways to avoid SQL injection:

1. Bind parameter names:


Query query=session.createQuery(hql);
query.setString( " name " ,name);

2. Bonding the parameter position:


Query query=session.createQuery(hql);
query.setString(0,name1);
query.setString(1,name2);
...

3. setParameter () method:


Query query=session.createQuery(hql); 
query.setParameter( " name " ,name,Hibernate.STRING);

4. setProperties () method:


Entity entity=new Entity();
entity.setXx( " xx " );
entity.setYy(100);
Query query=session.createQuery( " from Entity c where c.xx=:xx and c.yy=:yy  " ); 
query.setProperties(entity);

5. HQL splicing method, which is the most commonly used, easy to ignore and easy to be injected, is usually used to filter the special characters of parameters. It is recommended that you use StringEscapeUtils. escapeSql () method of Spring toolkit to filter parameters:


public static void main(String[] args) {
  String str = StringEscapeUtils.escapeSql("'");
  System.out.println(str);
}

Output: ''

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: