Should I get data using methods of an object or using jpa queries?

132 Views Asked by At

I have a java project and I am using JPA, so I have entity classes and the correspective database tables. Everything is set and ready and is working fine. From my database I can simply retrieve an object using a JPA query (for exemple getById()) and from this object I can get every other data I need, without using other queries. I was wondering if this is good practice or if I should use queries for getting all needed data.

Example:

  • First approach: Get the main object from the database using EntityManager.getObjectById(1) and get its children using object.getChildren().

  • Second approach: Get the main object from the database using EntityManager.getObjectById(1) and get its children using CriteriaQuery.select(Root).where(CriteriaBuilder.equal(Root.get("parent"), object)) getting a ResultList from the query.

Also, would this improve or worsen performance?

I searched for a while on google and stackoverflow but I couldn't find any information. I would expect the first approach to be fine.

2

There are 2 best solutions below

0
Rikkarth On

Just an idea, but maybe you can make some sort of method that measures how much time it takes to perform one and the other.

public static void main(String[] args) {
        // Measure the time before the method call
        long startTime = System.nanoTime();

        // Call the method you want to track
        exampleMethod();

        // Measure the time after the method call
        long endTime = System.nanoTime();

        // Calculate the elapsed time in milliseconds
        long elapsedTime = (endTime - startTime) / 1_000_000;
        System.out.println("The method took " + elapsedTime + " milliseconds to run.");
    }
0
Kaiak On

In my opinion, the second approach is the better one, but it really depends on how you configured your entities relationships and your use case.

If your parent entity has a lot of EAGER relationships (because lets say that you need them when you actually want the parent), get the parent each time only to access one of the child is going to generate lot of unnecessary join.

In the scenario of having all the relationship LAZY, I'm not really sure if there is a difference between the two approach, because the child is going to be loaded only when accessed anyway.

As a rule of thumb, it's better to let the database get the data for you when it's possible instead of process it by yourself later.