【问题标题】:How to create an object with constructor using hql query?如何使用 hql 查询创建带有构造函数的对象?
【发布时间】:2021-10-09 17:39:14
【问题描述】:

我在数据库中有两个表(CAR_BODY 和 MOTOR)。我正在编写 hql 查询请求。我需要从此表中获取 3 列并创建 DTO 对象。

表: 车体 | ----------------| 身份证 | 重量 | NUMBER_OF_DOORS | SPARE_WHEEL |

MOTOR
ID
ENGINE_DISPLACEMENT
TORQUE
NUMBER_OF_CYLINDERS

DTO 对象:

public class CarInf{
        private float weight;
        private float engineDisplacement;
        private float torque;

        public CarInf(float weight, float engineDisplacement, float torque) {
            this.weight = weight;
            this.engineDisplacement = engineDisplacement;
            this.torque = torque;
        }

        public float getWeight() {
            return weight;
        }

        public void setWeight(float weight) {
            this.weight = weight;
        }

        public float getEngineDisplacement() {
            return engineDisplacement;
        }

        public void setEngineDisplacement(float engineDisplacement) {
            this.engineDisplacement = engineDisplacement;
        }

        public float getTorque() {
            return torque;
        }

        public void setTorque(float torque) {
            this.torque = torque;
        }
    }

这是我在存储库界面中的方法:

@Query(nativeQuery = true,  value = "select new CarInf(cb.weight, m.engineDisplacement, m.torque) from Motor as m join CarBody as cb on m.id = cb.id where m.id = ?1")
    public List<CarInf> getCarInf(Long id);

但我得到 org.hibernate.exception.SQLGrammarException: could not extract ResultSet。

我的错误是什么?

【问题讨论】:

  • 当你使用nativeQuery = true 你的查询变成了真正的SQL。 HQL 不是 nativeQuery。
  • 还将?1 更改为:id

标签: java hibernate hql


【解决方案1】:
            String hql = "select s.svamAccNo, s.svamBrh, s.svamCustCode, l.lfcuTit1, l.lfcuSur1, l.lfcuOth1, s.svamAtmcdInName, s.svamAtmcdMothersMname "
                + " from Svam s, Lfcu l, Svp sv "
                + " where s.svamCustCode = l.lfcuCode "
                + " and s.svamProd = sv.id.svpsProd "
                + " and s.svamSubProd = sv.id.svpsSubProd "
                + " and s.svamAccNo = :p_acc_no ";

        Query query = em.createQuery(hql);
        query.setParameter("p_acc_no", kixcCustomerDetailsRequestDto.getAccountNo());
        query.setParameter("p_branch", kixcCustomerDetailsRequestDto.getBranch());
        

        List<Object[]> resultList = query.getResultList();

        Object[] obj = resultList.get(0);
        kixcCustomerDetailsRequestDto.setAccountNo((String) obj[0]);

你可以使用 HQL,除了像这个例子一样编写原生查询(原生查询可能导致运行时异常),并将查询结果作为对象数组的列表,并将它们设置到你的 POJO 对象中。

PS:- 如果您的查询返回单行,您可以使用 query.getSingleResultList() 方法获取结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多