How is SQL injection typically stopped in a Spring/Hibernate setup

Matthew Stopa picture Matthew Stopa · Jan 27, 2011 · Viewed 20.4k times · Source

I hate the Ruby language because it's not statically typed but the more time I spend with Spring/Hibernate I appreciate more of Ruby on Rails' features. Specifically the fact that their Active Record model prevents SQL injection for you. How is this issue typically handled with a Spring/Hibernate stack? Does either one come with a scrubbing toolkit of some sort, to make sure your user input is safe?

This isn't much of an issue on an insert if you are just inserting DAO's, but it's a major issue when using Select statements.

Answer

gutch picture gutch · Jan 27, 2011

SQL injection should not be a risk when you're using Hibernate - as long as you're using it properly.

Hibernate queries are either written in HQL (Hibernate's SQL-like query language) or implemented using object-oriented Criteria API.

HQL is the most common and most recommended. Typically you would write an HQL query like this:

    Subscription sub = (Subscription) sessionFactory.getCurrentSession()
        .createQuery("from Subscription sub where sub.verification = :verification")
        .setString("verification", verification)
        .uniqueResult();

In this form you are protected from SQL injection, because Hibernate passes in the string as a parameter; it cannot be interpreted as part of the SQL.

However if you behave badly an write a query like this...

    Subscription sub = (Subscription) sessionFactory.getCurrentSession()
        .createQuery("from Subscription sub where sub.verification = '" + verification + "'")
        .uniqueResult();

...then you're not protected from SQL injection. However you should never be writing queries like this! I don't think any framework would protect you if you append strings to your queries.

Finally, if you use the Hibernate Criteria API you are automatically protected from SQL injection; because Hibernate builds the underlying query when you're using the Criteria API it does so in a way that prevents SQL injection.