Member-only story
How to prevent SQL injection in your Java Spring Boot Application
SQL injection is a type of attack that allows a user to interfere with the queries that an application makes to its database. It is one of the most common web hacking techniques, being a top 5 every single year.
The attack works by injecting malicious SQL statements into an entry field for execution (e.g., to dump the database contents to the attacker).
Therefore, you can think of why you should protect your application against these attacks. Here are the main ways you can do that:
Use an ORM such as JPA
Using an ORM (Object Relational Mapper) like JPA allows you to make simple queries to your database without any need to write SQL. It automatically treats the arguments as values and therefore becomes immune to SQL Injection.
Here is an example of how a repository class would look like using JPA:
What if you need custom queries?
If your application needs more complex queries then you will need to use the @Param & @Query in your repository class. Here is an example of how you could use them:
By using the @Param data annotation along with @Query you are making sure all of the parameters needed to execute the query will always be treated as values and never as queries or conditions.