【问题标题】:Entity mapping to DTO实体映射到 DTO
【发布时间】:2018-09-13 17:57:51
【问题描述】:

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

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

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

}

因此,我收到了包含 GameCatalog 对象和长编号的对象列表:

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

Foo.class 看起来像:

@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;
}

我打算使用 MapStruct 来映射带有 DTO 的模型,但我不能这样做,因为 'findMostPlayable' 以上述方式返回结果。

如何在这里实现映射?

我应该使用 JPA JPQL 方式还是休眠功能,如投影等?

【问题讨论】:

    标签: spring-boot jpa mapping


    【解决方案1】:

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

    例如

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 2021-10-28
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      相关资源
      最近更新 更多