Spring JPA 实体可以实现 Projection 接口吗?

Can a Spring JPA Entity implement a Projection interface?

提问人:jaco0646 提问时间:10/24/2023 更新时间:10/24/2023 访问量:47

问:

基于接口的投影是 Spring JPA 中一个方便的功能,它允许存储库返回不同的接口。举个简单的例子,这个实体...

@Entity
@Table(name = "entity")
@Getter
@Setter
@ToString
public class MyEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String foo;
    private String bar;
}

...可以省略本机查询的字段和结果。

public interface EntityDTO {
    String getFoo();
    String getBar();
}

@Repository
public interface EntityRepository extends CrudRepository<MyEntity, Integer> {
    @Query(nativeQuery = true, value = "select * from entity where id = :id")
    EntityDTO findDtoById(int id);
}

以上作品...除非我希望实体本身实现投影接口。

public class MyEntity implements EntityDTO

这种关系看起来很自然,因为实体实际上确实实现了接口,并且服务方法不应该关心它们是从实体还是其他投影读取;但实现投影会导致查询异常。

org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.Object[]] to type [EntityDTO]

有没有办法使 JPA 代理成为不相关的接口,即使它是由 实现的?EntityDTOMyEntity

java spring-boot spring-data-jpa 投影

评论


答: 暂无答案