Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot JPA Query for not null

Tags:

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.

like image 828
Bhetzie Avatar asked Nov 17 '16 15:11

Bhetzie


People also ask

How do you write not equal in JPA query?

When using Jpql, the correct operator for "not equal" is <> . So, update your code like this: return em.

How does JPA handle null values?

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.

Does Spring JPA return empty list or null?

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.

Is null in JPQL?

Following example shows how to use IS NULL to find properties values which have not been set.


1 Answers

You can do that easily in your Interface

public interface EntityRepository extends CrudRepository<Batch, String> {   
    Iterable<Entity> findByStatusIdNotNull();
}

See the docs for more options

like image 175
baao Avatar answered Sep 17 '22 18:09

baao