Search code examples
databasespring-dataspring-data-jpasql-injection

Is Spring Data JPA safe against SQL injection


I am trying to find information about Spring Security JPA and if methods like .save() are protected from sql injection.

For instance I have object Customer. that I want to persist to my database. I am using CustomerRepository Spring implementation to operate on that entity. Customer's constructor is using parameters from the user. When everything is staged I am invoking .save(). Is this safe against sql injection or Should I do the check up first?


Solution

  • .save() is safe, only the usage of native queries is vulnerable.

    List results = entityManager.createNativeQuery("Select * from Customer where name = " + name).getResultList();
    

    You can make native queries safe also, if you use a parameter.

    Query sqlQuery = entityManager.createNativeQuery("Select * from Customer where name = ?", Customer.class);
    List results = sqlQuery.setParameter(1, "John Doe").getResultList();