Hello everyone, I created two tables User and Account One user can have multiple accounts

This field is in the User entity.

@OneToMany(cascade = CascadeType.ALL, mappedBy = "user") private Set<Account>accounts; 

This field is essentially

 @ManyToOne @JoinColumn(name = "user_id") private User user; 

The accounts in the table will be the id_user field. How to write a request to hibernate to find the user's accounts by name and phone number.

I write like this, and hibernate does not accept

 Query query = entityManager.createQuery( "select account from account where user.name=:name AND user.number=:number"); 

    2 answers 2

     from Account e where e.user.name=:name AND e.user.number=:number 

    Try this.

    • Thank you so much, it helped, a little confused by this "e.user.name". That is, we go through the table of accounts in the table of users and in the field name? - Igor Dianin
    • We have to specify to which entity the fields in the query relate, in hql this is done through an alias. The documentation recommends using the name of an entity class in lowercase as them: from Account as account . But this is not critical. - user320999 7:34 pm
    • thank you so much - Igor Dianin

    Something like this should look like:

     List<Account> accounts = HibernateSessionFactoryUtil .getSessionFactory() .openSession() .createQuery("FROM Account WHERE user = '" + name + "' AND number = '" + number + "'") .list();