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.
Query. Object getSingleResult() Execute a SELECT query that returns a single untyped result.
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.
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.
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.
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With