Search code examples
springhibernatehibernate-criteria

Get last record with criteria api


everyone. My task is to get the last added record from my database. Since the last of the records in the database has the maximum id, I wrote a method like this, but it always returns null to me.

@Override
    public Address getLast() {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Address> criteriaQuery = criteriaBuilder.createQuery(Address.class);
        Root<Address> root = criteriaQuery.from(Address.class);
        criteriaQuery
                .select(root)
                .orderBy(criteriaBuilder.desc(root.get(Address_.id)));
        TypedQuery<Address> findAllSizes = entityManager.createQuery(criteriaQuery);
        return findAllSizes.getResultStream().findFirst().orElse(null);
    }

Solution

  • All works fine. All I needed to add was add @Transactional on the method which calls the specified method