Skip to content

N+1 queries when fetching N→1 relationship (Example: Address → Person) using JDO #505

Description

@t-perez-r

When querying a list of Address entities in JDO (DataNucleus), each Address references a Person (N→1 relationship).
However, querying for Person through Address causes an additional SQL query for each element in the result list, leading to an N+1 query problem.

Example models:

@PersistenceCapable
public class Address {
    @PrimaryKey Long id;
    private String street;
    private Person person; // N -> 1
}
@PersistenceCapable
public class Person {
    @PrimaryKey Long id;
    private String name;
}

Problem:

When executing a query like:

Query<?> query = pm.newQuery(Adress.class);
query.setResult("distinct person");
List<?> results = (List<?>) q.execute();
for (Object obj : results) {
    Person pers = (Person) obj;
    NucleusLogger.GENERAL.info("Person: id=" + pers.getId() + " name=" + pers.getName()); // Triggers additional query
}

It results in one query for the list, and one extra query per each element.

Notes:

  • Using a fetch plan does not prevent the extra queries.
  • In my application, all the necessary fields are already available, but it still issues a database query when accessing the related entity.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions