使用JPA在JPQL中是否可以替代本机查询的“ GROUP_CONCAT”?

时间:2019-08-07 11:36:09

标签: java mysql spring-boot jpa jpql

我正在尝试使用jpql和JPA来获取配置文件的配置文件菜单。我的“个人资料”和“ ProfileMenus”实体之间存在多对一的关系。

我尝试研究这些答案,但找不到任何可行的解决方案。

QBluetoothLocalDevice

How to add non-standardized sql functions in Spring Boot application?

Registering a SQL function with JPA and Hibernate

我也通过此链接,似乎和我的问题相同, https://vladmihalcea.com/hibernate-sql-function-jpql-criteria-api-query/

使用本机查询时,我可以使用以下查询获取数据:

ProjectPath\android\app\

上面的查询为我提供了数据,

"SELECT
 GROUP_CONCAT(pm.user_menu_id SEPARATOR ',')
 AS profile_menu_ids,
 p.description
 FROM profile p
 LEFT JOIN profile_menu pm ON p.id = pm.profile_id
 WHERE
 p.id =:profileId
 AND
 pm.status = 'Y'
 GROUP BY p.id"

使用JPA的jpql中是否有任何方法或替代方法来获得如上所述的结果?

1 个答案:

答案 0 :(得分:0)

您可以考虑使用FluentJPA,它支持任何自定义功能:

public ProfileMenuGroup getMenuIdsByProfile(int profileId) {
    FluentQuery query = FluentJPA.SQL((Profile p,
                                       ProfileMenu pm) -> {
        String menuIds = alias(GROUP_CONCAT(pm.getUserMenuId(), ","),
                                            ProfileMenuGroup::getProfileMenuIds);
        String description = alias(p.getDescription(), ProfileMenuGroup::getDescription);

        SELECT(menuIds, description);
        FROM(p).LEFT_JOIN(pm).ON(p == pm.getProfile());
        WHERE(p.getId() == profileId && pm.getStatus() == "Y");
        GROUP(BY(p.getId()));
    });
    return query.createQuery(em, ProfileMenuGroup.class).getSingleResult();
}

查询产生以下SQL(profileId是自动绑定的):

SELECT GROUP_CONCAT(t1.user_menu_id SEPARATOR ',') AS profile_menu_ids,
                                    t0.description AS description 
FROM profile t0  LEFT JOIN profile_menu t1  ON (t0.id = t1.profile_id) 
WHERE ((t0.id = ?1) AND (t1.status = 'Y')) 
GROUP BY  t0.id

给出以下类型声明:

@Entity
@Data // lombok
@Table(name = "profile")
public class Profile {
    @Id
    private int id;

    private String description;
}

@Entity
@Data // lombok
@Table(name = "profile_menu")
public class ProfileMenu {
    @Id
    private int id;

    @ManyToOne
    @JoinColumn(name = "profile_id")
    private Profile profile;

    private int userMenuId;

    private String status;
}

@Tuple
@Data // lombok
public class ProfileMenuGroup {

    private String profileMenuIds;

    private String description;
}