Question

I have the following MySQL statement:

  "SELECT * FROM $this->tableName WHERE news_publication_id = '" + newsPublicationId + "' AND list_order > '" + listOrder +"' ORDER BY list_order LIMIT 1"

I started on the data handling path by first doing an Hibernate DAO layer.

It had the following criteria based method:

  @Override
  public NewsHeading findNextWithListOrder(NewsPublication newsPublication, int listOrder) {
    Criteria criteria = getSession().createCriteria(getPersistentClass());
    criteria.add(Restrictions.eq("newsPublication", newsPublication));
    criteria.add(Restrictions.gt("listOrder", listOrder)).addOrder(Order.asc("listOrder")).setMaxResults(1);
    return (NewsHeading) criteria.uniqueResult();
  }

And it works just fine.

Then I tried doing a JPA2 repository layer.

It now has the following JPQL based method:

  @Query("SELECT nh FROM NewsHeading nh WHERE nh.newsPublication = :newsPublication AND nh.listOrder > :listOrder ORDER BY nh.listOrder ASC LIMIT 1")
  public NewsHeading findByNextListOrder(@Param("newsPublication") NewsPublication newsPublication, @Param("listOrder") int listOrder);

But it doesn't work. Because the LIMIT clause is not valid.

So I wonder what to do.

Can I still use the criteria based method of above in this JPA2 repository layer ?

I would like to avoid trusting the client to pass the limit value and prefer to hard code that value (of 1) into my layer.

Also, that statement returns only one object and so there is no pagination needed.

Any tip would be most welcomed.

Kind Regards,

Stephane Eybert

Was it helpful?

Solution

You can probably this with a PageRequest. http://docs.spring.io/spring-data/jpa/docs/1.6.2.RELEASE/reference/html/repositories.html#repositories.core-concepts

Hibernate wants you to do setMaxResults() on the Query object, but JPA doesn't interface with that directly.

Other option would be to use a @NamedNativeQuery

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top