Generated select contains some fields multiple times

Hello,

I’m not very experienced with hibernate. I have two entities Client and Attribute like following ones:

@Entity
public class Client {
    @Id 
    @Column 
    private UUID id;

    @OneToMany(mappedBy = "client", cascade = CascadeType.PERSIST, orphanRemoval = true)
    private final Set<Attribute> attributes = new HashSet<>();
}
@Entity
public class Attribute {
    @Id 
    @Column 
    @GeneratedValue
    private UUID id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="fk_client")
    private Client client;

    @Column
    private String name;

    @Nationalized
    @Column
    private String value;
}

There is a bidirectional association between the two. It’s managed by child entity.

I was investigating generated queries by hibernate when attributes collection is initialized in the moment when it’s firstly accessed (I’m aware of n+1 queries issue, but in my use-case I’ll need attributes not for all clients and only in few cases, so it seems default lazy loading is appropriate here) and the query looks like:

select
    attributes0_.fk_client as fk_clien4_1_0_,
    attributes0_.id as id1_1_0_,
    attributes0_.id as id1_1_1_,
    attributes0_.fk_client as fk_clien4_1_1_,
    attributes0_.name as name2_1_1_,
    attributes0_.value as value3_1_1_ 
from
    attribute attributes0_ 
where
    attributes0_.fk_client=?

When i was debugging it it turned out that

  • fk_clien4_1_0_ comes from collection key column - AbstractCollectionPersister.keyColumnNames
  • id1_1_0_ comes from collection element column - AbstractCollectionPersister.elementColumnReaderTemplates
  • id1_1_1_, fk_clien4_1_1_, name2_1_1_ and value3_1_1_ comes from AbstractEntityPersister

I was wondering if all fields in the select is really necessary. Is that expected behavior? It seems that fk_client and id is fetched two times unnecessarily.

Is there a way how to instruct the hibernate to select only entity fields and not collection fields? Or the other way around? Or I might have wrongly declared the association?

Any thought would be more than welcome, thank you.

I was wondering if all fields in the select is really necessary. Is that expected behavior? It seems that fk_client and id is fetched two times unnecessarily.
Is there a way how to instruct the hibernate to select only entity fields and not collection fields? Or the other way around? Or I might have wrongly declared the association?
Any thought would be more than welcome, thank you.

Hi! Your analysis is correct and that is one of the things that we fixed in Hibernate 6.0.