首页 > 解决方案 > 排除对象的字节字段

问题描述

我试图从我的对象查询中排除字节字段,因为有数百或数千个报告,并且从数据库中查询它需要很长时间。

public class Reports
{
     private int id;
     
     private String reportName;
     
     @Lob
     @Basic(fetch= FetchType.LAZY)
     private byte[] file;
     
     private Date createdDate;
}

我尝试为此设置休眠字节增强功能如何设置 Hibernate Gradle 插件以进行字节码增强?但是当我查询所有报告时,我仍然得到文件。我在这里错过了什么吗?

标签: spring-boothibernatemaven

解决方案


字节码增强应该会有所帮助,但也许您没有正确配置它,或者您使用的 Hibernate 版本有错误。我需要了解详细信息或查看重现的测试用例来帮助您。

您可以尝试java.sql.Blob改用它保证是惰性的并且不需要字节码增强。

除此之外,我建议您使用 DTO 投影来实际获取您需要的数据。我认为这是Blaze-Persistence Entity Views的完美用例。

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

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

@EntityView(Reports.class)
public interface ReportsDto {
    @IdMapping
    int getId();
    String getReportName();
    Date getCreatedDate();
    Set<ReportRowDto> getRows();

    @EntityView(ReportRows.class)
    interface ReportRowDto {
        @IdMapping
        Long getId();
        String getName();
    }
}

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

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

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

DTO 投影根据实体模型进行验证,它只会获取必要的内容。当投影过于复杂时,Spring Data Projections 会退回到“仅”包装实体,而 Blaze-Persistence Entity-Views 会改变查询,就好像您是手工编写的一样 :)


推荐阅读