【问题标题】:JPQL how to create new DTO using Select with collection parameterJPQL 如何使用带有集合参数的 Select 创建新的 DTO
【发布时间】:2020-09-25 16:21:02
【问题描述】:

我正在尝试使用存储库直接从数据库中从实体投射 DTO。

@Query(value = "SELECT NEW com.jm.online_store.model.dto.ProductDto(p.id, p.comments) FROM 
    Product p WHERE p.id = :id")
ProductDto getCommentProductDto(@Param("id") Long productId);

但是我不断收到错误

java.sql.SQLSyntaxErrorException:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以了解在 '.作为 col_1_0_ 来自产品 product0_ 内部加入评论 cmets1_ 在 product0_ 上。在第 1 行

在我尝试将 Collection 作为查询构造函数参数传递之前,一切都可以正常工作。

我的 DTO 课程

public class ProductDto {

    private java.lang.Long id;
    private Collection<Comment> comments;

    public ProductDto(java.lang.Long id, Collection<Comment> comments) {
        this.id = id;
        this.comments = comments;
    }

    public ProductDto(java.lang.Long id) {
        this.id = id;
    }

    public ProductDto() {
    }

    public java.lang.Long getId() {
        return id;
    }

    public void setId(java.lang.Long id) {
        this.id = id;
    }

    public Collection<Comment> getComments() {
        return comments;
    }

    public void setComments(Collection<Comment> comments) {
        this.comments = comments;
    }
}

任何建议都将受到高度赞赏,现在已经坚持了几天......

【问题讨论】:

    标签: sql spring hibernate dto


    【解决方案1】:

    这是不可能的,您不能在 JPQL 构造函数语法中将集合作为参数传递。

    这是Blaze-Persistence Entity Views 的完美用例。

    我创建了该库以允许在 JPA 模型和自定义接口或抽象类定义模型之间轻松映射,例如 Spring Data Projections on steroids。这个想法是您按照自己喜欢的方式定义目标结构(域模型),并通过 JPQL 表达式将属性(getter)映射到实体模型。

    使用 Blaze-Persistence Entity-Views 的用例的 DTO 模型可能如下所示:

    @EntityView(Product.class)
    public interface ProductDto {
        @IdMapping
        Long getId();
        Set<CommentDto> getComments();
    
        @EntityView(Comment.class)
        interface CommentDto {
            @IdMapping
            Long getId();
            String getComment();
        }
    }
    

    查询是将实体视图应用于查询的问题,最简单的就是通过 id 进行查询。

    ProductDto a = entityViewManager.find(entityManager, ProductDto.class, id);

    Spring Data 集成让您可以像使用 Spring Data Projections 一样使用它:https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      相关资源
      最近更新 更多