首页 > 解决方案 > 升级到 Spring Boot 2.5.4 后未应用预测

问题描述

由于某种原因,升级到 Spring Boot 2.5.4 后不再应用投影。我真的想不通为什么。

我有一个类WhoDidWhatWhen(我在示例中更改了类/变量名):

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class WhoDidWhatWhen {

  @Id
  private Long id;

  @ManyToOne(fetch = FetchType.EAGER)
  private User who;

  @NotNull private String what;

  @NotNull @PastOrPresent private Date when;
}

我在与上述类相同的包中有一个投影:

@Projection(
    name = "whoDidWhatWhenProjection",
    types = {WhoDidWhatWhen.class})
public interface WhoDidWhatWhenProjection {
  @Value("#{target.id}")
  long getId();

  User getWho();

  String getWhat();

  Date getWhen();
}

最后我有了我的 RestRepository:

@RepositoryRestResource(exported = false, excerptProjection = WhoDidWhatWhenProjection.class)
public interface WhoDidWhatWhenRepository
    extends PagingAndSortingRepository<WhoDidWhatWhen, Long>, JpaSpecificationExecutor<WhoDidWhatWhen> {}

由于某种原因,投影/摘录没有被拾取和应用,我只是不知道为什么。

我什至尝试手动注册到投影,但无济于事:

@Configuration
public class RestConfiguration implements RepositoryRestConfigurer {
  public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
    config.getProjectionConfiguration().addProjection(WhoDidWhatWhenProjection.class);
  }
}

有谁之前经历过这个吗?

标签: javaspring-boothibernate

解决方案


我不知道您的特定问题的答案,但我想为您提供一个替代方案,即Blaze-Persistence Entity Views。您可以将其想象成类似于 Spring Data Projections 的类固醇,其映射会影响 SQL 并因此提高性能。映射经过完全类型验证以避免运行时意外,并且集成是无缝的。

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

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

@EntityView(WhoDidWhatWhen.class)
public interface WhoDidWhatWhenProjection {
    @IdMapping
    Long getId();
    String getWhat();
    Date getWhen();
    UserDto getWho();

    @EntityView(User.class)
    interface UserDto {
        @IdMapping
        Long getId();
        String getName();
    }
}

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

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

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

Page<WhoDidWhatWhenProjection> findAll(Pageable pageable);

最好的部分是,它只会获取实际需要的状态!


推荐阅读