• 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();
     }
    

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

  • 相关阅读:
    高并发的一些处理意见
    TP5单元测试
    你真的会玩SQL吗?和平大使 内连接、外连接
    微信公众号第三方平台开发概况
    MVC的基类
    Android TextView中显示图片
    Android之assets资源
    通用分页存储过程
    到处都是坑的微信支付V3之 微信支付回调页面
    微信公众平台无高级接口账号获取用户基本信息
  • 原文地址:https://www.cnblogs.com/tilv37/p/9477036.html
Copyright © 2020-2023  润新知