在Hibernate5.3.1中,HQL语句使用"?"参数占位符运行报错:
Caused by: org.hibernate.QueryException:
Legacy-style query parameters (`?`) are no longer supported; use JPA-style ordinal parameters (e.g., `?1`) instead
并且:在Query查询时:setInteger()等方法已过时:
解决办法:
1.将HQL语句中的"?"改为JPA-style:
String hql = "from Student where age > ?0 and score < ?1";
2.方法过时问题解决:使用setParameter():
List<Student> list = createQuery .setParameter(0, 21) .setParameter(1, 95.0) .list();
3.使用别名方式写HQL语句:
String hql = "from Student where age > :myage and score < :myscore";
总结:3种方式对应CODE:
// 1:将HQL语句中的"?"改为JPA-style:
String hql = "from Student where age > ?0 and score < ?1";
Query createQuery = session.createQuery(hql);
List<Student> list = createQuery
.setInteger(0, 21)
.setDouble(1, 95)
.list();
// 2:使用setParameter():
String hql = "from Student where age > ?0 and score < ?1";
Query createQuery = session.createQuery(hql);
List<Student> list = createQuery
.setParameter(0, 21)
.setParameter(1, 95.0)
.list();
// 3:别名:要求必须以冒号开头:
String hql = "from Student where age > :myage and score < :myscore";
Query createQuery = session.createQuery(hql);
List<Student> list = createQuery
.setInteger("myage", 21)
.setDouble("myscore", 95)
.list();