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,如

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

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

转载于:https://www.cnblogs.com/tilv37/p/9477036.html

你可能感兴趣的:(Spring Data JPA查询指定列,并返回实体(改))