javahibernatelazy-loading

Hibernate custom finder SQL query doesn't return OneToMany relation


I have a User class that has a @OneToMany List<Address> property. Hibernate has created a join table between user and address. When a user logs in, I look for the user with a custom SQL query;

select * from user where username = ? and password = ?

This obviously returns all the other fields of user but not the List<Address>. Is there a way in Hibernate to also return the relational data without using custom queries?

Could I load the user through the custom query above, pull its ID, and then reload the user so that Hibernate loads all the fields? Are there any better ways?

@Entity
public class User {

    @Id
    @GeneratedValue
    @GenericGenerator(name = "incremental", strategy = "increment")
    private Long userID;

    @Column(nullable = false)
    private String username;

    @Column(nullable = false)
    private String email;

    @Column(nullable = false)
    private String password;

    @OneToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "user_address", 
        joinColumns = @JoinColumn(name = "userID"), 
        inverseJoinColumns = @JoinColumn(name = "addressID"))
    private List<Address> addresses;
}

@Entity
public class Address {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NonVisual
    public Long addressID;
}

Solution

  • Try using HQL as below:

    String queryString = "select u from User u left join u.addresses "+
                         "where u.username = :userName and u.password = :password";
    

    EDIT: Sample code to execute HQL

    String queryString = "select u from User u left join u.addresses "+
                         "where u.username = :userName and u.password = :password";
    Query query = session.createQuery(queryString );
    query.setParameter("userName", userNameValue);
    query.setParameter("password", passwordValue);
    List<User> users = query.list();