1

This is the entity Utente; as you can see, there is a field autenticazione that is another entity, called Autenticazione

@Entity
@Table(name = "utente")
@Component
public class Utente implements Serializable{
    ...
    @OneToOne(mappedBy = "utente", cascade = CascadeType.ALL)
    @Valid
    private Autenticazione autenticazione;  
    ...
}

this is the entity Autenticazione

@Component
@Entity
@Table(name = "autenticazione")
public class Autenticazione implements Serializable{
    ...
    @OneToOne(targetEntity=Utente.class)    
    @JoinColumn(name="utente", referencedColumnName="id") 
    private Utente utente;      

    @Column(name = "username")
    @Size(min = 3, max = 20)
    @Pattern(regexp="^[A-Za-z0-9.-_]*$")
    private String username;
    ...
}

I have to make a query that allow me to get the object Utente from the database, searching by the value of the the field username of the object Autenticazione, that is a field of the entity Utente.

I should do something like this:

Criteria criteria = getCurrentSessionFactory().createCriteria(Utente.class);
criteria.add(
             Restrictions.eq("autenticazione.username",            
             utenteForSearch.getAutenticazione().getUsername())
             );

Is it possibile to use Hibernate and use as "where" a field of an Entity that is an Entity itself?

Thank you

MDP
  • 4,177
  • 21
  • 63
  • 119

1 Answers1

1

Commenter (@Dragan Bozanovic) is correct, you want this:

Criteria criteria = getCurrentSessionFactory().createCriteria(Utente.class);
crit.createAlias("autenticazione", "autenticazione");
criteria.add(
             Restrictions.eq("autenticazione.username",            
             utenteForSearch.getAutenticazione().getUsername())
             );
winklebort
  • 98
  • 4