Get single row in JPA

Viewed 51260

How to get single row from entity in JPA?

Table: Employee

    @Id
    private int empId;
    private String empName;
    ...    

JPA by default return List. I`m trying to fetch single row.

EmployeeRepository :-

    public Employee findByEmpName(String empName);

Another way is to do it, @Query should be use.

    @Query(value="select e from Employee e where empName = ?1 limit 1", nativeQuery=true)
    public Employee findByEmpName(String empName);

How can i ensure that it return single row and correct result. Any help appreciated.. Thanks in advance.

5 Answers

There is an out of the box solution, in repository you can name method as findFirstBy... or findTopBy..., that should do the thing.

You can find more in Spring reference documentation

In case someone wants just a single row from a database using JpaRepository (spring-data-jpa), I found this very useful:

repository.findAll().stream().findFirst().orElseThrow(...)

Since this is a stream, I suppose that rows (or rather: Objects) are fetched row by row.

Related