0

Is insert statement like this is safe enough? Do I have to check if it's not SQL Injectionable?

@Autowired
private SessionFactory sessionFactory;

public void add(String title, String region, String def, String rangeStart,
        String rangeEnd, Date extradition, Date expiration) {
    Session session = null;

    session = this.sessionFactory.getCurrentSession();
    Query query = session
            .createSQLQuery(
                    "INSERT INTO operators VALUES(NULL,:title,:region,:def,:rangeStart,:rangeEnd, :extradition, :expiration )")
            .setString("title", title).setString("region", region)
            .setString("def", def).setString("rangeStart", rangeStart)
            .setString("rangeEnd", rangeEnd)
            .setDate("extradition", extradition)
            .setDate("expiration", expiration);
    int updated = query.executeUpdate();
}
Tony
  • 3,605
  • 14
  • 52
  • 84
  • 1
    First, ask yourself this: what *is* [SQL Injection](http://en.wikipedia.org/wiki/SQL_injection)? Then you should be able to answer yourself :) Note that SQL Injection only covers a very specific scenario - when the *shape* of a query is altered. (Which also means that it could be injection-free but still not "safe".) – user2864740 May 21 '14 at 20:00

1 Answers1

3

Yes, it is safe enough for SQL Injection attacks. Note that Query#executeUpdate will use a PreparedStatement behind the scenes for you to set the data for the parameters, which makes this statement safe enough.

PreparedStatement will write the Strings content directly in the specified fields, escaping any undesired value.

Still, note that if you have a bad design of your queries, you will be open to SQL Injection attacks. For example, if you create the query but append the String manually:

String sqlOpenToSqlInjection = "FROM operators WHERE stringField = " + stringVariable;
Query query = session.createSQLQuery(sqlOpenToSqlInjection);
//code to execute query...

More info:


Looks like you're using Hibernate as well, so it would be better if you save the entity. This would be similar but less code to handle/maintain.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • If there isn't more to come then this is rather a comment. Especially from a 35k+ user. – juergen d May 21 '14 at 20:00
  • @juergend I know, but that's the only sentence to answer OP's question. Should we vote to close? I don't think so because it is a valid question. – Luiggi Mendoza May 21 '14 at 20:02
  • @LuiggiMendoza it is a valid question though, but may be duplicate of http://stackoverflow.com/questions/16807399/sql-injection-prevention-with-hibernate this one? – padawan May 21 '14 at 20:07
  • @OnurÇağırıcı Hibernate as is already prevents SQL queries for SQL Injection since it uses `PreparedStatement`s for the created queries. That's the answer. – Luiggi Mendoza May 21 '14 at 20:08