How to set parameters for a Named Query

2020-06-06 06:23发布

问题:

Hi I have a Named Query

@NamedQuery(name = "StudyplanCategory.findByStatusAndLimit",
            query = "SELECT s FROM StudyplanCategory s WHERE 
            s.status =:status LIMIT s.start=:start,s.end=end")

I want to set the limit like this:

@NamedQuery(name = "StudyplanCategory.findByStatusAndLimit", 
            query = "SELECT s FROM StudyplanCategory s WHERE 
            s.status =:status LIMIT s.start=:start,s.end=end")

But this is showing error at the start up of the Server. I am using the below code to call the query in the DAO class:

Query query = entityManager.createNamedQuery("StudyplanCategory.findByStatusAndLimit");
int end=(start*pageNumber);
query.setParameter("status", status);
query.setParameter("start", start);
query.setParameter("end", end);
return (List<StudyplanCategory>) query.getResultList();

Start and End Parameters needs to be set. Please Help.

回答1:

As @DataNucleus said, LIMIT is not a valid keyword in JPQL. That's not the way to specify how many rows to return. This is how you do it:

@NamedQuery(name = "StudyplanCategory.findByStatusAndLimit", 
        query = "SELECT s FROM StudyplanCategory s WHERE 
                    s.status =:status")

And this would be the code to call the named query:

Query query = entityManager.createNamedQuery("StudyplanCategory.findByStatusAndLimit");
int end=(start*pageNumber);
query.setParameter("status", status);
query.setFirstResult(start);
query.setMaxResults(end - start);
return (List<StudyplanCategory>) query.getResultList();


标签: hibernate jpa