Gert Kommer Gert Kommer - 2 months ago 8
Java Question

JPA PersistenceException: Class name could not be resolved

I'm trying to create a method to get a project by the project name from GAE, but I'm getting the following error.

javax.persistence.PersistenceException: Class name TestProject could not be resolved


I get this error in the following piece of code on the line where the
if
statement starts

public Project getProjectByProjectName(String projectName){
EntityManager em = EMFService.get().createEntityManager();
Query q = em.createQuery("SELECT p FROM Project p WHERE p.projectName = " + projectName);
Project p = null;
if(q.getResultList().size() != 0){
p = (Project) q.getSingleResult();
}
return p;
}


I called the method like this:
getProjectByProjectName("TestProject");


Why does java think that testproject is a class? Is the query wrong?

Thanks in advance :)

Answer

If the project name is TestProject, the query should be

SELECT p FROM Project p WHERE p.projectName = 'TestProject'

and not, as you are doing

SELECT p FROM Project p WHERE p.projectName = TestProject

All that wouldn't happen if you stopped using String concatenation to pass parameters to queries. This makes your code vulnerable to JPQL injection attacks. And it will break as soon as a project name contains a single quote. Use parameters:

Query q = em.createQuery("SELECT p FROM Project p WHERE p.projectName = :name");
q.setParameter("name", projectName);  
Comments