I've created a class which does a query based by some filters that are filled in the frontend application. Basically there are 3 filters: "Title", "startDate" and "endDate". Here are the problems that I'm facing:
When I send the title alone without the dates, the system works ok; When I send the title with dates, the system works ok, returning the list of objects correctly; When I send the dates without the title, the system throws a NullPointerException.
public class RacRepositoryImpl implements RacRepositoryQuery {
@PersistenceContext
private EntityManager entityManager;
@Override
public List<Rac> filtrar(RacFilter racFilter) throws Exception {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Rac> query = builder.createQuery(Rac.class);
Root<Rac> from = query.from(Rac.class);
Predicate predicate = builder.and();
//title
if (racFilter.getTitulo() != null & racFilter.getTitulo().length() > 2) {
predicate = builder.and(predicate,
builder.like(from.<String>get("titulo"), "%"+racFilter.getTitulo()+"%"));
}
//startDate
if (racFilter.getDataInicial() != null) {
predicate = builder.and(predicate,
builder.greaterThanOrEqualTo(from.<Date>get("dataHora"), racFilter.getDataInicial()));
}
//finalDate
if (racFilter.getDataFinal() != null) {
predicate = builder.and(predicate,
builder.lessThanOrEqualTo(from.<Date>get("dataHora"), racFilter.getDataFinal()));
}
// here it throws the NullPointer exception when I don't send the title information
TypedQuery<Rac> typedQuery = entityManager.createQuery(
query.select(from )
.where( predicate )
);
try {
List<Rac> results = typedQuery.getResultList();
return results;
} catch (Exception e) {
throw new Exception("not found");
}
}
I'm not posting the other classes because I've debugged and the attributes are coming well to this class. The problem is when I don't send the field "title", that means, when it is null (it's not required), the query doesn't work
Most probably the source of NullPointerException is here:
//title
if (racFilter.getTitulo() != null & racFilter.getTitulo().length() > 2) {
Please replace "&" by "&&" and see the result.