首页 > 解决方案 > 在本机查询中映射 JPA 中的值

问题描述

我有一个带有 JPA 的 Spring Boot 应用程序。我需要将查询中的值映射到实体。

样本实体

@Entity
@Table(name = "questions")
@DynamicUpdate
public class Question{

 @Id
 @Column(nullable = false)
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;

 @Lob
 private String description;

 @Transient
 private int noOfViews;

}

示例查询

@Repository
public interface QuestionRepository extends JpaRepository<Question, Long> {

@Query(value = "select q.*,  2 NO_OF_VIEWS from questions q 
order by q.id DESC ", countQuery = "select count(*) from questions q order by q.id DESC " ,nativeQuery = true)
        Page<Question> findQuestions(Pageable pageable);

}

我需要将值设置为 noOfViews 字段。对此有任何想法吗?Spring 有 RowMapper 接口,但没有找到任何用于 spring boot 的东西。

标签: sqlspring-bootjpaspring-data-jpa

解决方案


您可能想查看SqlResultSetMapping 文档

JPA项目也有一个很好的例子。看这个例子

摘自以上链接。

JPA 2.1 引入了新的 SqlResultSetMapping 类型 ConstructorResult,它允许将结果集行的列映射到构造函数调用,该调用可以很好地与值对象结合使用。

TBH,我没有在@Transient 字段上尝试过这个,但我已经将@NamedNativeQuery 与Projection DTO 一起使用。


推荐阅读