Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named entity graph JOINS results (need distinct option) in Spring Data JPA

I'm using @NamedEntityGraph annotation to load a graph from database.

@NamedEntityGraph(
    name = "Firma.uredjivanje",
    attributeNodes = {
            @NamedAttributeNode(value="prevodi", subgraph = "prevodi")
    },
    subgraphs = {
            @NamedSubgraph(
                    name = "prevodi",
                    attributeNodes = {
                            @NamedAttributeNode(value = "jezik", subgraph = "jezik")
                    }
            )
    }
)

In the Spring Data JPA repository, I'm using annotation:

@EntityGraph(value="Firma.uredjivanje", type = EntityGraph.EntityGraphType.LOAD)
List<Firma> getByAktivna(boolean aktivna);

Everything works as expected, expect that all relations are joined, and I get duplicate Firma entities (because of JOIN). Instead of a List with entity id's {1,2,3}, I get {1,1,1,2,2,3}.

What is the best way to get distinct entities (if this is not a bug ofcourse).

like image 656
Bojan Vukasovic Avatar asked Jun 19 '14 19:06

Bojan Vukasovic


People also ask

How do I create an entity graph in JPA?

In Spring Data JPA, we can define an entity graph using a combination of @NamedEntityGraph and @EntityGraph annotations. Or, we can also define ad-hoc entity graphs with just the attributePaths argument of the @EntityGraph annotation.

What is JPA in spring data?

One of the important features in Spring Data JPA or simply JPA is the ability to specify fetch plans using Entity Graphs. This is useful since it allows you to customize the data, which is retrieved with a query or find operation.

How to define a named entity graph?

The definition of a named entity graph is done by the @NamedEntityGraph annotation at the entity. It defines a unique name and a list of attributes (the attributeNodes) that shall be loaded. The following example shows the definition of the entity graph graph.Order.items which will load the list of OrderItem of an Order. public class Order { ... }

How do I use @namedentitygraph in JPA?

With @NamedEntityGraph First, we can use JPA's @NamedEntityGraph annotation directly on our Item entity: @Entity @NamedEntityGraph (name = "Item.characteristics", attributeNodes = @NamedAttributeNode ("characteristics") ) public class Item { //...


1 Answers

Found the answer... Since NamedEntityGraph does JOIN in database, it selects all entities without DISTINCT. So the solution is to use Distinct in method name...

@EntityGraph(value="Firma.uredjivanje", type = EntityGraph.EntityGraphType.LOAD)
List<Firma> getDistinctByAktivna(boolean aktivna);
like image 61
Bojan Vukasovic Avatar answered Oct 20 '22 21:10

Bojan Vukasovic