Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
Spring Data conditionally fetch children

I've read Spring Data JPARepository: How to conditionally fetch children entites. But I want to use convenient JPA annotations rather than manual join all children.

Say I have the following Model:

@Entity
public class UserModel extends BaseModel<User> {

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<CredentialModel> credentialList = new ArrayList<>();

    @ManyToMany
    @JoinTable(
            name = "users_actions",
            joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "action_id", referencedColumnName = "id")
    )
    private List<ActionMode> actionList = new ArrayList<>();
}

Fetching credentialList and actionList can be a time consuming operation (join fetches, etc). I do not want to auto fetch credentialList nor actionList . But when I access them, I expect them to be an empty List rather than LazyInitializationException.

Can I use the fields even when I did not specifically JOIN FETCH them in @Query. Just leave it to be an empty list.

If not, Is there anyway to achieve same needs?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Returning empty Collections would lead to a problem: You couldn't distinguish between a really empty collection and one, that just isn't lazily loaded. You could check for the collections before accessing them through org.hibernate.Hibernate.isInitialized(...) or PersistenceUnitUtil#isLoaded(...) in JPA2.

However I would suggest you to use Data-Transfer-Objects at this point. For the special use-case, where the collections are not needed, just build a similiar copy of your entity without that unnesseccary properties. Of course your DTO building must be done within an open session.

about 4 years ago · Santiago Trujillo Relatório

0

I think you are trying to do JOIN but not FETCH, may be just using child objects' attributes in where condition. I wonder something like this will work in JPQL.

@Query("Select u from UserModel u INNER JOIN u.credentialList c
 INNER JOIN u.actionList a")
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda