Search code examples
hql

How to perform left join in hql to fetch data


I am using following query to get data data database

String hql = "from Parameters s "
             +"left join fetch s.userValues as uv "
             + "where s.groupId=:gid "
             +"and uv.user.id=:uid  " ;

Above is my hql query here I am fetching data from Parameter and from userValues. This query is working properly if user have any value in userValues. This query is not fetching any value when there is no saved value for user in userValues.

My problem is Whether there should be data in userValues or not I want to fetch data from Parameters.

How to achieve this using hql?

I just want to do left join in hql to get first table values.


Solution

  • You probably want something like this. You need to left join the association to user also. Note that you should use the Hibernate mapping between Parameter and Group as below. But you will probably need to use grouping to remove duplicate results.

    String hql = "from Parameters s "
        + "join s.group g "
        + "left join fetch s.userValues uv "
        + "left join uv.user u "    
        + "where g.id=:gid "
        + "and (u.id=:uid or u is null) ";