2

I have the following entities:

@Entity
@NamedEntityGraph(name = "Text.WithRows", attributeNodes = { @NamedAttributeNode("rows") })
public class Text {
  @Id
  @Column(name = "uuid", nullable = false, unique = true)
  UUID uuid;

  @Column(name = "belongsTo")
  UUID belongsTo;

  @OneToMany
  @JoinColumn(name = "text_id")
  List<TextRow> rows;
}

@Entity
public class TextRow {
  @Id
  @Column(name = "uuid", nullable = false, unique = true)
  private UUID uuid;

  @Column(name = "content", nullable = false, length = 255)
  private String content;
}

I also have a Spring Data JPA Repository defined like this:

public interface TextRepository extends PagingAndSortingRepository<Text, UUID>, JpaSpecificationExecutor<Text> {
  @EntityGraph(value = "Text.WithRows", type = EntityGraphType.LOAD)
  List<Text> findAllByBelongsTo(UUID belongsTo)
}

I want to have the TextRows eagerly loaded, when I execute the find-Method from the repository. Therefore I introduced the NamedEntityGraph- and the EntityGraph-annotations in the code above.

I have 2 entries in the Text-table of my database having 3 entries in the TextRow-table each.

I expect the method findAllByBelongsTo to return a list with two Text-instances. Instead it returns a list containing 6 Text-instances.

I don't understand why this happens. Can someone please give me some guidance or a solution?

Thank you!

gdiquest
  • 125
  • 8

1 Answers1

2

Okay, it seems that what I am seeing is the intended behavior. Hibernate creates an SQL containing LEFT OUTER JOINS. This leads to n x m result rows of the parent table.

These SO questions describe my problem and gave a solution to me:

In short, I can annotate my repository like this:

public interface TextRepository extends PagingAndSortingRepository<Text, UUID>, JpaSpecificationExecutor<Text> {
  @EntityGraph(value = "Text.WithRows", type = EntityGraphType.LOAD)
  @Query("SELECT DISTINCT txt FROM Text txt WHERE txt.belongsTo = :belongsTo")
  List<Text> findAllByBelongsTo(@Param("belongsTo") UUID belongsTo)
}
Community
  • 1
  • 1
gdiquest
  • 125
  • 8