Search code examples
hibernateprepared-statementjpql

createNativeQuery()& createQuery() with NamedParameter


I have an Entity CategoryElement :

@Entity(name = "CategoryElement ")
@Table(name = "category_element")
public class CategoryElement {
 
 @Column(columnDefinition = "varchar(100)", name = "farsi_name",nullable = false)
 private String farsiName;

  /* and other stuff*/  

I want to write a query for this entity same as we did in preparedStatement but i got this Syntax Error cannot resolve symbol
There is my query:

public List<CategoryElement> findByName(String farsiName) {
    EntityManager manager = HibernateUtils.getEntityManager();
    Query query = manager.createQuery("select o from CategoryElement as o where o.farsi_name=:param");
    query.setParameter("param",farsiName);
    List categoryElementList = query.getResultList();
    manager.close();
    return categoryElementList;
}

I got the Syntax Error in line 3 : cannot resolve symbol 'CategoryElement ' and also in line 4 I got the same message about param
I've tried the CreateNativeQuery() method like this :

Query query = manager.createNativeQuery("select * from category_element where farsi_name =: param", CategoryElement.class);  
query.setParameter("param",farsiName);    

but again I got the same message in line 2 for param
I check with this Link but it doesn't solve my problem .
I have no idea .

EDIT: I'm using jdk1.8 + tomcat 9 + Hibernate 5.4.27


Solution

    1. Try to replace this:
    @Entity(name = "CategoryElement ")
    

    by this:

    @Entity(name = "CategoryElement")
    

    I would suggest you completely remove name parameter in the @Entity annotation and leave just:

    @Entity
    

    as by default name already equals to the unqualified name of the entity class.

    1. As for your JPQL, I would suggest you to correct it in the following way:
    List<CategoryElement> categoryElementList = manager.createQuery(
       "select o from CategoryElement o where o.farsiName = :param",
       CategoryElement.class
    )
    .setParameter("param", farsiName)
    .getResultList();
    

    And several notes here:

    • You should use entity field names in the JPQL, not table column names.

    • It is better to avoid usage of java raw types. So, you should prefer to use those EntityManager.createQuery methods that return TypedQuery<T>

    1. As for your native query, you can correct it in the following way:
    List<CategoryElement> categoryElementList = manager.createNativeQuery(
       "select * from category_element where farsi_name = :param",
       CategoryElement.class
    )
    .setParameter("param",farsiName)
    .getResultList();