使用JPA和Hibernate将查询结果映射到DTO的最佳方法 - Vlad Mihalcea

20-06-11 banq

DTO:

@NamedNativeQuery(
    name = "PostDTO",
    query = """
        SELECT
           p.id AS id,
           p.title AS title
        FROM Post p
        WHERE p.created_on > :fromTimestamp
        """,
    resultSetMapping = "PostDTO"
)
@SqlResultSetMapping(
    name = "PostDTO",
    classes = @ConstructorResult(
        targetClass = PostDTO.class,
        columns = {
            @ColumnResult(name = "id"),
            @ColumnResult(name = "title")
        }
    )
)
public class PostDTO {
 
    private Long id;
 
    private String title;
 
    public Long getId() {
        return id;
    }
 
    public void setId(Number id) {
        this.id = id.longValue();
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
}

SQL投影执行如下:

List<PostDTO> postDTOs = entityManager
.createNamedQuery("PostDTO")
.setParameter(
    "fromTimestamp",
    Timestamp.from(
        LocalDateTime.of(2020, 1, 1, 0, 0, 0)
            .toInstant(ZoneOffset.UTC)
    )
)
.getResultList();

点击标题见其他更多方法。

         

猜你喜欢