Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get single row in JPA

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.

like image 216
Akkave Avatar asked May 25 '17 06:05

Akkave


People also ask

How can I get single result in JPA?

Query. Object getSingleResult() Execute a SELECT query that returns a single untyped result.

How do you limit records in JPA?

Using Native SQL to control the max number of records Hibernate and JPA applications are able to use native SQL statements. Therefore, you can use the SQL SELECT LIMIT statement to limit the number of records from a resultset.

How do I limit query results in Spring Data JPA?

Spring Data JPA supports keywords 'first' or 'top' to limit the query results (e.g. findTopBy....). An optional numeric value can be appended after 'top' or 'first' to limit the maximum number of results to be returned (e.g. findTop3By....). If this number is not used then only one entity is returned.

How JPQL works?

Java Persistence Query languageIt is used to create queries against entities to store in a relational database. JPQL is developed based on SQL syntax. But it won't affect the database directly. JPQL can retrieve information or data using SELECT clause, can do bulk updates using UPDATE clause and DELETE clause.


3 Answers

You don't need to "ensure" anything.

If you dont have a collection of sort specified as return (e.g. List<Employee> instead of Employee ) and your query return more than one result it will launch a javax.persistence.NonUniqueResultException: result returns more than one elements.

If your query return more rows and you want only one of those either add a condition to differentiate which one of those rows you actually want or, if they are the same, add a good old distinct

How can i ensure that it return single row and correct result.

That's your job when writing the query

like image 190
Zeromus Avatar answered Sep 30 '22 02:09

Zeromus


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

like image 39
milosdju Avatar answered Sep 30 '22 03:09

milosdju


JPA have a method to fetch a single row getSingleResult, but it's recommended to fetch a list and extract the first element over getResultList.

See: Example

like image 27
fireandfuel Avatar answered Sep 30 '22 03:09

fireandfuel