Hibernate命名参数未绑定错误:获取指定userId购物车项失败求助
解决Hibernate QueryException: Named parameter not bound错误
这个报错的核心原因是:你在HQL语句中定义了命名参数:userId,但执行查询前没有将方法接收的userId参数绑定到这个命名参数上,Hibernate无法找到参数值,因此抛出该异常。
修正后的代码
@Override @Transactional public List<Cart> getCartItems(long userId) { // get the current hibernate session Session currentSession = sessionFactory.getCurrentSession(); // create a query Query<Cart> theQuery = currentSession.createQuery("from Cart as c where c.user_id= :userId", Cart.class); // 绑定命名参数到传入的userId值 theQuery.setParameter("userId", userId); // execute query and get result list List<Cart> cartItems = theQuery.getResultList(); // return the results return cartItems; }
关键说明
- 所有在HQL中以
:xxx形式定义的命名参数,必须通过Query.setParameter()方法绑定对应的参数值,否则Hibernate无法解析参数 - 额外注意:如果你的
Cart实体类中对应的属性名是userId(而非数据库表的user_id),建议将HQL语句中的c.user_id改为c.userId,遵循面向对象的属性引用规范,避免因字段名不匹配引发其他问题
内容的提问来源于stack exchange,提问作者Jayden pak
相关产品推荐
相关产品推荐

