Question

I have the following generic method in my own Persistence-class:

@SuppressWarnings("unchecked")
public static <T> T getByCondition(Class<T> clazz, String database, Object id){
    EntityManager em = getEntityManager(database);
    Query q = em.createQuery("SELECT t FROM "+clazz.getName()+" t WHERE t.id = :id").setParameter("id", id);
    T result = (T) q.getSingleResult();
    return result;
}

The method works pretty fine, but I am concerned about the "+clazz.getName()+" in the Query as I am not very sure if this could lead to an sql-injection.

Is there a better way to declare the Class I want to search for in the Query?

Thanks in advance for your answers. :-)

Was it helpful?

Solution

The code you've posted is safe, as the class Class is final and can't be extended and is inexorably tied to the class it represents which means you won't be able to pass it a fake class where getName() returns a custom string, furthermore you cannot have a class name which includes the punctuation necessary to use SQL injection. e.g., this is impossible:

class ' or '1'='1; DROP TABLE USERS; --
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top