【问题标题】:How to Get Result on from JPA Custom @Query in Spring boot to DTO如何在 Spring Boot 中从 JPA 自定义 @Query 获取结果到 DTO
【发布时间】:2020-06-16 17:54:05
【问题描述】:

我想在不使用元组的情况下将此查询的结果获取到 DTO。

@Repository 公共接口 CustomMapRepository 扩展 JpaRepository {

@Query(
    nativeQuery = true,
    value = "select  i.id as  permissionId, p.id as projectId,p.name as projectName,i.user_id as userId,\n" +
        "case " +
        "when  i.scopes is not null then i.scopes\n" +
        "when i.scopes is null   then \"[{'edit':false},{'create':false},{'update':flase},{'delete':false},{'view':false}]\" end as scopes \n" +
        "from   internal_permission i  \n" +
        "right join project p\n" +
        "on i.project_id=p.id\n" +
        "where \n" +
        "(user_id=:userId or user_id is null )and \n" +
        "p.space_id=:spaceId )")
List<CustomMapDTO> findBySpaceIdAndUserId(@Param("spaceId") Long spaceId, @Param("userId") String userId);

}


the DTO Class 

公共类 CustomMapDTO 实现 Serializable {

private  String permissionId;
private  Long projectId;
private  String projectName;
private  String userId;
private  String  scopes;

//..getter 和 setter }



【问题讨论】:

  • 为什么你有一个name 参数(应该链接到结果映射)。去掉它。还请解释什么不起作用。
  • 为什么要创建nativeQuery?请阅读文档:docs.spring.io/spring-data/jpa/docs/current/reference/html/…
  • 好的,我会删除它,你有什么办法可以解决这个问题以从查询中获取结果

标签: spring-boot jpa


【解决方案1】:
  List<CustomMapDTO> res= ((Session)this.em.getDelegate()).createSQLQuery(
        "\n select p.id as projectId,p.name as projectName, i.id as permissionId,i.user_id as userId,\n" +
            "case\n" +
            "  when  i.scopes is not null then i.scopes\n" +
            "  when i.scopes  is null   then \"[{'edit':false},{'create':false},{'update':flase},{'delete':false},{'view':false}]\" end as scopes \n" +
            "from internal_permission i right join project p \n" +
            "on i.project_id=p.id \n" +
        "where \n" +
        "((user_id=:userId or user_id is null ) " +
        " and \n" +
        "(p.space_id=:spaceId))")
        .addScalar("projectId", LongType.INSTANCE)
        .addScalar("projectName", StringType.INSTANCE)
        .addScalar("permissionId", LongType.INSTANCE)
        .addScalar("userId", StringType.INSTANCE)
        .addScalar("scopes", StringType.INSTANCE)
        .setResultTransformer(new AliasToBeanResultTransformer( CustomMapDTO.class))
        .setParameter("spaceId",spaceId)
        .setParameter("userId",userId)
        .unwrap(org.hibernate.query.Query.class)
        .getResultList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-21
    • 2021-05-08
    • 2018-01-04
    • 2016-03-08
    • 2018-12-25
    • 1970-01-01
    • 2011-04-30
    • 2021-12-01
    相关资源
    最近更新 更多