JPQL and Join Table

后端 未结 1 1299
执笔经年
执笔经年 2021-02-02 02:49

My understanding of SQL and JPQL are not that great and I have been trying to create a JPQL query of the following sql statement:

select group.* from user, user_         


        
相关标签:
1条回答
  • 2021-02-02 03:14

    Using JPQL it would be:

    TypedQuery<Group> query = em.createQuery(
        "SELECT DISTINCT g FROM User u LEFT JOIN u.groupCollection g " +
        "WHERE u = :user", Group.class);
    query.setParameter("user", user);
    List<Group> = query.getResultsList();
    

    where em is your EntityManager and user is the instance of the User class for which to load group list. If you only have the user id, change with:

    TypedQuery<Group> query = em.createQuery(
        "SELECT DISTINCT g FROM User u LEFT JOIN u.groupCollection g " +
        "WHERE u.id = :user", Group.class);
    query.setParameter("user", userId);
    

    It would be better to use a Set or SortedSet (or maybe a List if the user can be in the same group more than once) instead of a Collection.

    0 讨论(0)
提交回复
热议问题