【问题标题】:Map values in JPA in native query在本机查询中映射 JPA 中的值
【发布时间】:2019-04-05 23:07:15
【问题描述】:

我有一个带有 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 的东西。

【问题讨论】:

    标签: sql spring-boot jpa spring-data-jpa


    【解决方案1】:

    你可能想看看SqlResultSetMappingDocumentation

    JPA 项目也有一个很好的例子。 See this example

    摘自上述链接。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-08
      • 2017-04-29
      • 2014-06-25
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      相关资源
      最近更新 更多