zoukankan      html  css  js  c++  java
  • Spring Data JPA查询指定列,并返回实体(改)

    现有PostEntiy实力,包含各种属性,如:

    /**
     * @Auther: DingShuo
     * @Date: 2018/7/18 11:09
     * @Description:
     */
    @Entity
    public class PostEntity {
        @Id
        @GenericGenerator(name = "system-uuid", strategy = "uuid2")
        @GeneratedValue(generator = "system-uuid")
        String id;
    
        @Column(nullable = false)
        String title;
    
        @Column(nullable = false,columnDefinition="TIMESTAMP")
        @Temporal(TemporalType.TIMESTAMP)
        @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
        Date createTM;
    
        @Lob
        @Column(columnDefinition="TEXT")
        String postContent;
    
        //余下略
    }
    

    想只查询标题title和时间createTM,按照常规用法应该返回的是List<Object[]>,如

    **
     * @Auther: DingShuo
     * @Date: 2018/7/18 11:57
     * @Description:
     */
    @Repository
    public interface PostEntityRepo extends JpaRepository<PostEntity,String> {
         @Query(value = "select p.title,p.createTM from PostEntity p")
        List<Object[]> test();
     }
    

    但是这样还是重新遍历再取值,现在想实现如Mybatis里面的查询resultmapper,该怎么办?

    先创建一个查询结果的实体,如

    /**
     * @Auther: DingShuo
     * @Date: 2018/8/14 19:02
     * @Description:
     */
    public class TestDTO {
    
    
        String title;
    
        Date createTM;
    
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public Date getCreateTM() {
            return createTM;
        }
    
        public void setCreateTM(Date createTM) {
            this.createTM = createTM;
        }
    
        public TestDTO(String title, Date createTM) {
            this.title = title;
            this.createTM = createTM;
        }
    }
    

    在改动JPA的@Repository类中,修改查询方法,如

    **
     * @Auther: DingShuo
     * @Date: 2018/7/18 11:57
     * @Description:
     */
    @Repository
    public interface PostEntityRepo extends JpaRepository<PostEntity,String> {
         @Query(value = "select new com.haramasu.daomin2.dto.TestDTO(p.title,p.createTM) from PostEntity p")
        List<TestDTO> test();
     }
    

    此后查询结果就是被转为预设的结果实体了。

  • 相关阅读:
    好听的歌 好音乐
    dubbox编译
    [HDU3038]How Many Answers Are Wrong(并查集)
    [POJ1733]Parity game(并查集 + 离散化)
    [POJ1703]Find them, Catch them(并查集)
    [luoguP2024] 食物链(并查集)
    [luoguP3355] 骑士共存问题(二分图最大独立集)
    火星探险问题
    [CODEVS1917] 深海机器人问题(最小费用最大流)
    [CODEVS1916] 负载平衡问题(最小费用最大流)
  • 原文地址:https://www.cnblogs.com/tilv37/p/9477036.html
Copyright © 2011-2022 走看看