I have an @Entity Video
having a one-to-many relation with a List<Tag> tags
as one of its fields. I use the following @Repository
using Spring Data to get the most popular tags:
@Repository
public interface TagRepository extends CrudRepository<Tag, Integer>{
@Query("SELECT t FROM Tag t WHERE (SELECT SUM(v.views) FROM Video v WHERE t MEMBER OF v.tags) > 0")
public List<Tag> findMostViewedTags(int maxTags);
}
The Query is processed and considered valid by Spring, I tested the generated SQL vs my database locally and it returned 2 Tags. In my Code however, I receive the value Null when I call the method findMostViewedTags(100).
The Query lookup strategy is the default "CREATE_IF_NOT_FOUND".
Null
instead of a List<Tag>
with size() 2?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 .
You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null.
Returns: the saved entity; will never be null. Throws: IllegalArgumentException - in case the given entity is null.
The JPA specification defines that during ordering, NULL values shall be handled in the same way as determined by the SQL standard. The standard specifies that all null values shall be returned before or after all non-null values. It's up to the database to pick one of the two options.
annotation to specify a custom JPQL or native SQL query. Spring Data JPA provides the required JPA code to execute the statement as a JPQL or native SQL query. Your preferred JPA implementation, such as, Hibernate or EclipseLink, will then execute the query and map the result.
Select Query In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.xml file.
At runtime, Spring Data JPA will create your repository implementations with the common CRUD methods. You can then perform CRUD operations without writing a single line of data access code.
If a List<Object> is the return value of the method in the defined interface, the method should never return Null. 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.
List<Object>
is the return value of the method in the defined interface, the method should never return Null
.I have experienced similar problem. The cause was that I was using Mockito and have not correctly mocked the data with when()
.
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