入门 05 - Query接口
我们可以透过 org.hibernate.Query接口的实例来进行查询,透过Query接口,您可以先设定查询参数,之后透过setXXX()等方法,将指定的参数值填入,而不用每次都撰写完整的HQL,直接来看个例子:
Query query = session.createQuery("select user.name from User as user where user.age = ? and user.sex = ?");
query.setInteger(0, 25);//设定参数0为第一参数;1为第二个参数?
参数设定见书(陈天河 ssh集成) 的第406页
query.setCharacter(1, 'M');
List names = query.list();
for (ListIterator iterator = names.listIterator(); iterator.hasNext(); ) {
String name = (String) iterator.next();
System.out.println("name: " + name);
}
在设定参数值时,必须依照 ? 所设定的顺序,并使用对应型态的setXXX()方法,一个执行的例子如下:
log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select user0_.name as x0_0_ from USER user0_ where (user0_.age=? )and(user0_.sex=? )
name: Bush
您可以使用命名参数:参数(Named Parameter)来取代这个方法,这可以不用依照特定的顺序来设定参数值,并拥有较好的可读性,直接来看个例子:
Query query = session.createQuery("select user.name from User as user where user.age = :age and user.sex = :sex");
query.setInteger("age", 25);
query.setCharacter("sex", 'M');
List names = query.list();
for (ListIterator iterator = names.listIterator(); iterator.hasNext(); ) {
String name = (String) iterator.next();
System.out.println("name: " + name);
}
设定命名参数时,在建立Query时先使用:后跟着参数名,之后我们就可以在setXXX()方法中直接指定参数名来设定参数值,而不用依照特定的顺序。
我们也可以将HQL撰写在程序之外,以避免硬编码(hard code)在程序之中,在需要修改HQL时就很方便,在*.hbm.xml中使用<query/>标签,并在<![CDATA[与]] >之间撰写HQL,撰写的位置是在</hibernate-mapping>之前,例如:
User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="onlyfun.caterpillar.User" table="USER">
<id name="id" type="string">
<column name="user_id" sql-type="char(32)" />
<generator class="uuid.hex"/>
</id>
<property name="name" type="string" not-null="true">
<column name="name" length="16" not-null="true"/>
</property>
<property name="sex" type="char"/>
<property name="age" type="int"/>
</class>
<query name="com.abin.User">
<![CDATA[
select user.name from User as user where user.age = :age and user.sex = :sex
]]>
</query>
</hibernate-mapping>
<query>的name属性用来设定查询外部HQL时的名称依据,使用的例子如下:
Query query = session.getNamedQuery("com.abin.User");
query.setInteger("age", 25);
query.setCharacter("sex", 'M');
List names = query.list();
for (ListIterator iterator = names.listIterator(); iterator.hasNext(); ) {
String name = (String) iterator.next();
System.out.println("name: " + name);
}