0

I have a class Usuario. User have association with UsuarioPerfil:

public class Usuario{

  /*Attributes*/

  @OneToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "id_usuario_perfil", referencedColumnName = "id", foreignKey = @ForeignKey(name = "fk_usuario_id_usuario_perfil"))
  @Getter
  @Setter
  private UsuarioPerfil usuarioPerfil;

  }

  public class UsuarioPerfil{

    /*Attributes*/
  }

I am performing queries using the Criteria, as follows:

  Session sessao = this.getEntityManager().unwrap(Session.class);
  sessao.createCriteria(Usuario.class).list();

However, in some cases wish list does not come in the data UsuarioPerfil entity, only the User. How can I accomplish this using Hibernate Criteria?

Note: I know this is possible using Hibernate or JPA Query

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
Luciano
  • 3
  • 5

1 Answers1

0

I don't believe you can explicitly do what you are asking with the Hibernate Criteria API because it is generally accepted practice to make associations LAZY and set them to EAGER on a case-by-case basis.

Therefore, change your mapping to use fetch = FetchType.LAZY and then in the cases where you need the association in your query, specify it as:

criteria.setFetchMode("usuarioPerfil", FetchMode.JOIN);

If you have access to JPA's EntityGraph annotations, I would strongly suggest you look into those as well. At a minimum, you can at least look at Hibernate's FetchProfile concept because those go along way to defining fetch strategies by name which helps keep code and queries much cleaner.

Naros
  • 19,928
  • 3
  • 41
  • 71