1

I have a HQL Query in JpaRepository:

public interface LineRepository extends JpaRepository<LineEntity , Integer>{
    @Query(
            value = "SELECT l from LineEntity l" +
                    "WHERE l.lineCode = :lineCode "
    )
    List<LineEntity> findAllByLineCode(
            @Param("lineCode")int lineCode
    );

}

I want to change this method to return a LineEntity. Limit just work on nativeQuery and i want put this into annotation

Morteza Jalambadani
  • 1,881
  • 5
  • 19
  • 30
  • Possible duplicate of [What is the LIMIT clause alternative in JPQL?](https://stackoverflow.com/questions/44565820/what-is-the-limit-clause-alternative-in-jpql) – Tom Aug 16 '18 at 12:44
  • You need to implement that as a native query. You can not use Limit in HQL because Limit is database vendor dependent so hibernate doesn't allow it through hql query. – David Jesus Jul 01 '20 at 19:40

4 Answers4

1

If there are a lot of LineEntity with the same LineCode then you need an extra attribute, that attribute can be the id, for example:

public interface LineRepository extends JpaRepository<LineEntity , Integer>{
    @Query(
            value = "FROM LineEntity li WHERE li.id = " +
                    "(SELECT max(l.id) FROM LineEntity l " +
                    "WHERE l.lineCode = :lineCode)"
    )
    LineEntity findFirstByLineCode(
            @Param("lineCode") int lineCode
    );
}
David Jesus
  • 1,041
  • 2
  • 17
  • 24
0

On the query object in hibernate you have a setMaxResults(int maxResults) method.

I am not use of how to put this into annotation but with the classical way it works like this:

Query q = session.createQuery("XXX").setMaxResults(1000);
q.list();
Orden
  • 441
  • 2
  • 11
0

If you want to do this without query, then we can use Pageable interface. Just do two steps.

1) In Controller

@RequestMapping("/getLineByLineCode/{code}")    
public @ResponseBody Page<LineEntity> getFirstUserByName(@PathVariable String code,Pageable pageable)
{
  // this pageable for single result.(first result will return)
    Page<LineCode> line = repository.findByCode(code,new PageRequest(0,1));
                                                        //(start index,upto index)
   return line;
} 

2) In Repository

public interface LineRepository extends JpaRepository<LineEntity , Integer>{
       Page<LineCode> findByCode(String code,Pageable pageable);
}
Angad Bansode
  • 619
  • 4
  • 13
0

As the documentation states

The results of query methods can be limited by using the first or top keywords, which can be used interchangeably. An optional numeric value can be appended to top or first to specify the maximum result size to be returned. If the number is left out, a result size of 1 is assumed

So to limit by 10 you can also use:

List<LineEntity> findTop10ByLineCode(int lineCode);
mtshaikh
  • 349
  • 3
  • 12