实体映射到DTO

时间:2018-04-04 08:42:58

标签: spring-boot jpa mapping

我想将查询结果映射到以下JPQL的DTO:

0 = {Object[2]@10670} 
 0 = {GameCatalog@10675} 
 1 = {Long@10676} 8968

结果,我收到了包含GameCatalog对象和Long number的对象列表:

@Entity
@Getter
@Setter
public class Foo{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "game_catalog_id", nullable = false)
    private GameCatalog game;

    private Long timeSpent;
}

Foo.class看起来像:

WebView

我计划使用MapStruct与DTO映射模型,但我不能这样做,因为' findMostPlayable'以这种方式返回结果。

我如何在这里实现映射?

我应该使用JPA JPQL方式还是像投影等hibernate功能?

1 个答案:

答案 0 :(得分:0)

要使用聚合函数获取查询结果,您可以创建自己的类而不是使用实体并使用它。

实施例

 public class MyFoo {

    private String game;
    private int duration;
    public String getGame() {
        return game;
    }
    public void setGame(String game) {
        this.game = game;
    }
    public int getDuration() {
        return duration;
    }
    public void setDuration(int duration) {
        this.duration = duration;
    }   
  }

@Repository
public interface FooRepository extends JpaRepository<Foo, Id> {

@Query("select new MyFoo(f.game as game, sum(f.timeSpent) as duration ) from foo f  group by f.game order by duration desc")
    List<MyFoo> findMostPlayable();

}
相关问题