2023-10-11

Java recursive entity search

I have a simple recursive method which intends to find the timestamp of an entity by the given Id. If there is no such Id, the result will be null so I'm gonna get a NPE, thus the catch block comes in, finds the next available Id and calls this function again with the new Id.

This works well so far, when the function is called again with the next available Id, it finds the entity, but when it tries to return the timestamp, myEntity becomes null and its a NPE again. I'm debugging in IntelliJ and stop the code just before this and myEntity does have an actual value here, before the return statement.

From this point the code just hangs and nothing visible happens. I guess there is something under the hood regarding to recursion, but couldn't figure it out yet.

Thanks in advance!

public LocalDateTime getInsertTimeById(Long id) {
        try {
            MyEntity myEntity = entityManager.find(MyEntity .class, id);
            return myEntity.getInsertTime();
        } catch (Exception e) {
            Long nextAvailableId = findNextAvailableId(id);
            return getInsertTimeById(nextAvailableId);
        }
    }

private Long findNextAvailableId(Long id) {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<Long> cq = cb.createQuery(Long.class);
        Root<MyEntity> root = cq.from(MyEntity.class);

        cq.select(cb.min(root.get("id"))).where(cb.gt(root.get("id"), id));

        TypedQuery<Long> query = entityManager.createQuery(cq);
        return query.getSingleResult();
    }

PS: I know that eventually the findNextAvailableId() won't find an Id, but handling of that is irrelevant at this point.

UPDATE: I couldn't find the problem, had to come up with an other solution which is as the commenters state preferable anyways:

public LocalDateTime getInsertTimeById(Long mindId, Long maxId) {
        LocalDateTime insertTime = getInsertTimeByIdQuery(mindId);
        if (insertTime != null) {
            return insertTime;
        }
        Long nextAvailableId = findNextAvailableId(mindId, maxId);
        if (nextAvailableId == null) {
            return null;
        }
        return getInsertTimeByIdQuery(nextAvailableId);
    }


No comments:

Post a Comment