【问题标题】:Why does setParameter not set the parameter?为什么 setParameter 不设置参数?
【发布时间】:2012-06-11 17:12:12
【问题描述】:

我正在使用以下代码来(尝试)查询数据库:

Query query = session.createQuery("from Trace where service = :service");
query.setParameter("service", clientRequest[0]);

其中 clientRequest[0] 来自字符串数组,服务变量是 POJO 中的字符串,映射到 MySQL 数据库中的 VARCHAR(45)。

当我运行这段代码时,Hibernate 将执行的 SQL 查询显示为:

Hibernate: select trace0_.traceId as traceId0_, trace0_.service as service0_, trace0_.longitude as longitude0_, trace0_.latitude as latitude0_, trace0_.timestamp as timestamp0_ from trace trace0_ where trace0_.service=?

这让我相信 clientRequest[0] 的值没有被正确设置为参数。

我已经检查了 clientRequest[0] 包含一个有效的字符串,它确实如此。我尝试了其他创建查询的方法,但这些都没有奏效,它们总是将服务显示为“?”,而如果我使用明显的:

Query query = session.createQuery("from Trace where service = 21");

它自然会给出正确的反应

Hibernate: select trace0_.traceId as traceId0_, trace0_.service as service0_, trace0_.longitude as longitude0_, trace0_.latitude as latitude0_, trace0_.timestamp as timestamp0_ from trace trace0_ where trace0_.service=21

什么可能会阻止 setParamater 正常工作?

【问题讨论】:

    标签: sql hibernate parameters hql


    【解决方案1】:

    它应该在日志中输出。 Hibernate 不会在查询字符串中记录参数。参数设置正确。未设置参数时,您会看到异常。

    如果您还想记录参数值,可以从here 找到一些说明。

    【讨论】:

    • 太棒了。在我验证之前,我会检查一下并做一些测试来确认。非常感谢。
    • 刚刚确认参数添加正确,我现在无法让日志记录工作,但您的回答完全正确。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2020-08-14
    • 2014-01-31
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 2017-12-10
    相关资源
    最近更新 更多