Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Ioannis Angelis
Added: Sep 14, 2021 5:26 PM
Views: 160
  1. EntityManager em = Persistence.createEntityManagerFactory("eWeatherPU").createEntityManager();
  2. CriteriaBuilder cb = em.getCriteriaBuilder();
  3. CriteriaQuery<Tuple> cq = cb.createTupleQuery();
  4. Root<Forecast> from = cq.from(Forecast.class);
  5. Join<Forecast, City> join = from.join(Forecast_.city);
  6. cq.multiselect(join, from);
  7.  
  8. Expression<Timestamp> fromDate = cb.currentTimestamp();
  9. Expression<Timestamp> toDate = cb.literal(Timestamp.valueOf(LocalDateTime.now().plusHours(24)));
  10. Path<String> city = join.get(City_.city);
  11. Path<Timestamp> date = from.get(Forecast_.forecastPK).get(ForecastPK_.dt);
  12. Predicate whereCity = cb.equal(city, cmbCities.getSelectedItem());
  13. Predicate whereDate = cb.between(date, fromDate, toDate);
  14. Predicate condition = cb.and(whereCity, whereDate);
  15. Order dateAsc = cb.asc(from.get(Forecast_.forecastPK).get(ForecastPK_.dt));
  16. cq.where(condition);
  17. cq.orderBy(dateAsc);
  18. List<Tuple> results = em.createQuery(cq).getResultList();
  19. em.close();