== How to fix it in Hibernate

=== Code examples

include::../../common/fix/code-rationale.adoc[]

==== Noncompliant code example

[source,java,diff-id=1,diff-type=noncompliant]
----
@RestController
public class ApiController
{
    @Autowired
    QueryProducer queryProducer;

    @GetMapping(value = "/authenticate")
    @ResponseBody
    public ResponseEntity<String> authenticate(
        @RequestParam("user") String user,
        @RequestParam("pass") String pass)
    {
        String query = "SELECT * FROM users WHERE user = '" + user + "' AND pass = '" + pass + "'";

        try {
          queryProducer
            .createNativeQuery(query)
            .getSingleResult();

        } catch (Exception e) {
            return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED);
        }

        return new ResponseEntity<>("Authentication Success", HttpStatus.OK);
    }
}
----

==== Compliant solution

[source,java,diff-id=1,diff-type=compliant]
----
@RestController
public class ApiController
{
    @Autowired
    QueryProducer queryProducer;

    @GetMapping(value = "/authenticate")
    @ResponseBody
    public ResponseEntity<String> authenticate(
        @RequestParam("user") String user,
        @RequestParam("pass") String pass)
    {
        String query = "SELECT * FROM users WHERE user = :user AND pass = :pass";

        try {
          queryProducer
            .createNativeQuery(query)
            .setParameter("user", user)
            .setParameter("pass", pass)
            .getSingleResult();

        } catch (Exception e) {
            return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED);
        }

        return new ResponseEntity<>("Authentication Success", HttpStatus.OK);
    }
}
----

=== How does this work?

include::../../common/fix/prepared-statements.adoc[]

