4

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?

1 Answer 1

1
  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.
Sign up to request clarification or add additional context in comments.

2 Comments

Am using the parameter that is passed to the function. May be my statement in scenario 2 gave a different meaning.Have modified.
Hey, did found an answer for the problem? I am facing same problem, if you know the solution then please tell me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.