I'm using spring boot JPAs and I want to only return values where the status id is not null. What's the best way to query for this?
Domain
@ManyToOne
@JoinColumn(name = "entity_status_id")
private entityStatusLookup entityStatusLookup;
EntityController
public interface EntityRepository extends CrudRepository<Batch, String> {
public Page<Entity> findByUploadUserOrderByUploadDateDesc(String userId, Pageable page);
public Entity findByEntityId(String entityId);
}
api
@RequestMapping(value="/entity/user", method=RequestMethod.GET)
public HttpEntity<PagedResources<Entity>> getEntityByUser(Pageable page, PagedResourcesAssembler assembler) {
String user = SecurityContextHolder.getContext().getAuthentication().getName();
Page<Enity> entityItems = entityRepository.findByUploadUserOrderByUploadDateDesc(user, page);
return new ResponseEntity<>(assembler.toResource(entityItems), HttpStatus.OK);
}
I realize that I could loop through the returned pages and look for nulls to remove, but I'd rather have the query just return values that are not null. I'm not sure what the best way to query for not null on the entity status id.
When using Jpql, the correct operator for "not equal" is <> . So, update your code like this: return em.
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.
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 . The problem is that a parameter is given to the method and is not used anywhere in the Query.
Following example shows how to use IS NULL to find properties values which have not been set.
You can do that easily in your Interface
public interface EntityRepository extends CrudRepository<Batch, String> {
Iterable<Entity> findByStatusIdNotNull();
}
See the docs for more options
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