gpt4 book ai didi

java - Hibernate createNativeQuery - 获取多个实体

转载 作者:行者123 更新时间:2023-12-02 10:34:01 24 4
gpt4 key购买 nike

我正在使用以下代码通过 hibernate 执行 native SQL 查询:

    Query zonesQuery = session.createNativeQuery(
"Select * \n" +
"FROM dbo.Structure AS S\n" +
"JOIN dbo.StructureLocationType AS SLT ON SLT.StructureId = S.Id\n" +
"WHERE SLT.LocationTypeId = :lc").addEntity(StructureEntity.class);

zonesQuery.setParameter("lc", locationTypeID);
List<StructureEntity> zones = zonesQuery.list();

所以它起作用了,它让我获得了 StructureEntity 列表

现在,因为我的 SQL 查询从 StructureLocationType 表中“加入”,是否有可能仍然使用单个查询来获取整个 StructureLocationType 行?

谢谢。

最佳答案

可以通过以下方式实现(注意 SQL 和实体别名中的大括号):

Query query = session
.createNativeQuery(
"SELECT {S.*}, {SLT.*} " +
"FROM dbo.Structure AS S " +
"JOIN dbo.StructureLocationType AS SLT ON SLT.StructureId = S.Id " +
"WHERE SLT.LocationTypeId = :lc")
.unwrap(SQLQuery.class)
.addEntity("S", StructureEntity.class)
.addEntity("SLT", StructureLocationTypeEntity.class)
.setParameter("lc", locationTypeID);


List<Pair<StructureEntity, StructureLocationTypeEntity>> result = ((List<Object[]>) query.list())
.stream()
.map(p -> Pair.of((StructureEntity) p[0], (StructureLocationTypeEntity) p[1]))
.collect(Collectors.toList());

关于java - Hibernate createNativeQuery - 获取多个实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53428634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com