Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityManager Native Query Syntax?

The following method uses the createNativeQuery() method of the Java entity manager:

   public List<Dog> findDogById(String id) {

        List<Dog> resultList = new ArrayList<>();
        try {
            resultList = persistence.entityManager().createNativeQuery(" SELECT * FROM DOG WHERE ID = '" + id+ "' ", DogEntity.class).getResultList();
        } catch (Exception e) {
        }
        return resultList;
    }

The issue that I am having is that this method is not returning results when I expect it to do so. I.e. when I run the queries directly through SQL Developer I get results, but the method does not return the same.

Is my Syntax correct? I am unsure about this:

" SELECT * FROM DOG WHERE ID = '" + id+ "' "

i.e. do I need both the ' and the " ?

like image 509
java123999 Avatar asked May 12 '26 21:05

java123999


1 Answers

Your syntax is correct but you have other problems in your code.

You are silently ignoring the exception. You are probably getting an exception, ignoring it and then returning the empty list:

    try {
        resultList = persistence.entityManager().createNativeQuery(" SELECT * FROM DOG WHERE ID = '" + id+ "' ", DogEntity.class).getResultList();
    } catch (Exception e) {
        // If an exception is thrown in this try block, you are ignoring it.
    }

If you use the query without parameter binding, you could have issues with SQL injection. To make an example, if someone sends 0' OR 1=1-- as the id in your function, the user get a full list of Dogs.

Use parameters and avoid these kind of problems, the queries are also more readable and less error prone:

.createNativeQuery(" SELECT * FROM DOG WHERE ID = ?1", DogEntity.class)
.setParameter(1, id)
.getResultList();
like image 64
David SN Avatar answered May 15 '26 10:05

David SN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!