balaaagi
balaaagi

Reputation: 512

JPA Query using native query returns null instead of list of entities

Using spring-data-jpa.

@Entity
@Table(name="employees")
Class Employee{
.
.
.
.

}

public interface EmployeeRepository extends CrudRepository<Employee,Long> {
  @Query(value = "SELECT * from employees where org_id=:orgId ",nativeQuery = true)
    public List<Employee> findByOrgId(@Param("orgId") String orgId);
}

When am calling the repository function it behaves pretty strange.

In Employees table there are two records for org_id =18.

Scenario 1: When am passing 18 to this function am able to get a result which is of type List. Iterating it am able to get the expected result

Scenario 2 When am passing an org id which is not present in the DB the it returns me null.

Am handling it using checking for null.

Is checking for null is the right way? Should the result should return a empty list instead of null?

Upvotes: 4

Views: 7526

Answers (1)

Alien
Alien

Reputation: 15908

  1. The normal behavior is indeed returning an empty list if no results are found. If a List<Object> is the return value of the method in the defined interface, the method should never return null.
  2. The problem is that a parameter is given to the method and is not used anywhere in the Query. For some reason Spring decides to return a Null in that case. Solution: remove the unused parameter or use the parameter in the Query.

Upvotes: 1

Related Questions