關於在Hibernate5.3.1中HQL語句使用"?"引數佔位符執行報錯的問題
阿新 • • 發佈:2019-02-08
在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();