簡體   English   中英

休眠本機查詢復雜構造函數映射

[英]hibernate native query complex constructor mapping

Java,Spring Data JPA

我有2個實體:

class Source {
  Integer id;
  String name;
}

class Item {
  Integer id;
  String name;
  Integer sourceId;
} 

我需要這樣的統計本機查詢結果:

 select s.id source_id, s.name source_name, count(i.id) item_count
 from source s
 left join item i on s.id = i.source_id
 group by s.id 

我想在Java對象MyResult中產生結果:

class MyResult {
  Source source;
  Integer itemCount;
  MyResult(Source source, Integer itemCount) {...}
}

最接近的解決方案是使用@SqlResultSetMapping,如下所示:

@SqlResultSetMapping(
    name = "MyResultMapping",
    entities = {
        @EntityResult(
             entityClass = Source.class,
                fields = {
                    @FieldResult(name = "id", column = "source_id"),
                    @FieldResult(name = "name", column = "source_name"),
                }
        ),
        ... 
        ???
    }
)

要么

@SqlResultSetMapping(
    name = "MyResultMapping",
    classes = {
        @ConstructorResult(
            targetClass = MyResult.class,
                columns = {
                    @ColumnResult(name = "???"),
                    ???
                }
        )
    }
)

對於第二個變體,我可以使用這樣的東西:

MyResult(Integer sourceId, String sourceName, Integer itemsCount) {
    this.source = new Source(sourceId, sourceName);
    this.itemsCount = itemsCount;
}

但是我希望它與@SqlResultSetMapping自動化...(因為我的真實對象更加復雜)

使用Spring Data JPA,最好使用投影來實現您的需求,例如:

public interface SourceWithItemCount {
    Source getSource();
    Integer getItemCount();
}

然后在您的Source資源庫中創建HQL查詢方法,如下所示:

public interface SourceRepo extends JpaRepository<Source, Integer> {
    @Query("select s as source, count(i) like itemCount from Source s left join Item i on i.sourceId = s.id group by s"
    List<SourceWithItemCount> getSourcesWithItemCount();
}

重要說明是對返回值使用別名( s as source等),它允許Spring Data JPA將其映射到projections屬性。

Hibernate 5.1+版中的Join on <condition>作品(如果我沒記錯的話),所以我建議您在對象之間創建經典的一對多關系,例如:

@Entity
class Source {
    @Id private Integer id;
    private String name;
    @OneToMany @JoinColumn(name = "source_id") private List<Item> items;
}

@Entity
class Item {
    @Id private Integer id;
    private String name;
} 

然后創建所有版本的Hibernate(和其他ORM提供程序)支持的JPQL查詢方法:

@Query("select s as source, count(i) like itemCount from Source s left join s.items i group by s"
List<SourceWithItemCount> getSourcesWithItemCount();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM