Get maximum table value (JPA) with Java 8

Asked

Viewed 219 times

1

I have a method in my DAO class that returns a general list of the table:

public List<ObjetoRisco> findAll() {
    return manager.createQuery("select o from ObjetoRisco o", ObjetoRisco.class).getResultList();
}

In my class Controller, I’m having a hard time filtering out the maximum value of the ID column using the Java 8 API. The closest I came to the desired result was this way:

Optional<Integer> maxId = objetoRiscoDao.findAll().stream().map(ObjetoRisco::getId).max(Integer::compare);
modelAndView.addObject("maxId", maxId);

But when I call on my JSP ${maxId}, I receive in response Optional[270]. In fact the 270 is the last id, but I’m not getting it as whole so I can manipulate it, like,: ${maxId + 1}.

  • 1

    @Maurydeveloper No need to add ```java in the code blocks. Since the question already has the [java] tag, the syntax Highlight is applied automatically, without having to specify the language. See more details in the FAQ: https://meta.stackexchange.com/q/184108/401803

3 answers

3

Simply "uncouple" the content of Optional:

Optional<Integer> maxId = objetoRiscoDao.findAll().stream().map(ObjetoRisco::getId).max(Integer::compare);
modelAndView.addObject("maxId", maxId.get());

Or rather:

Integer maxId = objetoRiscoDao.findAll().stream().map(Integer::new).max(Integer::compare).orElse(1); // Retorna valor padrão

Or:

Integer maxId = objetoRiscoDao.findAll().stream().map(Integer::new).max(Integer::compare).orElseGet(() -> 1 + 2); // Retorna algum cálculo ou resultado de função

Or else:

Integer maxId = objetoRiscoDao.findAll().stream().map(Integer::new).max(Integer::compare).orElseThrow(() -> new RuntimeException("Não existe máximo")); // Lança exceção caso deva existir máximo
  • Opa...your solution was much better than mine... I will use it. Thank you very much!!

  • 1

    @Cristian It’s not a matter of "better". This is the right way to work with Optional. The hashcode "works" by coincidence, since its current implementation is to return the number itself (but nothing prevents it from changing in future versions, as it is internal implementation detail). Not to mention that the hashcode returns zero if the value does not exist (remember, it is a Optional, value may not exist). Already use get and the methods orElse... is the right way to treat the result

0

I was able to solve using the resource below:

Integer max = maxId.hashCode();

Thank you!

0

Integer contained in Optional failed to be extracted:

modelAndView.addObject("maxId", maxId.get());

However worth remembers that this Optional can contain a null internally, so requires a treatment or check before extracting it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.