可以透過org.hibernate.Query介面的實例來進行查詢,透過Query介面,您可以先設定查詢參數,之後透過setXXX()等方法,將 指定的參數值填入,而不用每次都撰寫完整的HQL,直接來看個例子:
Session
session = sessionFactory.openSession();
Query query = session.createQuery("select user.name from User as user where user.age > ?");
query.setInteger(0, 25);
List names = query.list();
Iterator iterator = names.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
session.close();
Query query = session.createQuery("select user.name from User as user where user.age > ?");
query.setInteger(0, 25);
List names = query.list();
Iterator iterator = names.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
session.close();
在設定參數值時,必須依照 ? 所設定的順序,並使用對應型態的setXXX()方法,一個執行的例子如下:
Hibernate:
select user0_.name as col_0_0_ from user user0_ where
user0_.age>? momor caterpillar bush |