Hibernate中提供一种可以把HQL配置在Hibenate.hbm.xml中. 这样的好处,可以统一进行管理. 以及可以在其他Service中都能用到.
比如我们在User.hbm.xml中配置如下HQL语句:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="pack.java.model.UserInfo" schema="MBADMIN" table="USER_INFO"> <id name="uiid" type="java.lang.Long"> <column name="UIID" precision="10" scale="0"/> <generator class="sequence"> <param name="sequence">seq_user_info</param> </generator> </id> <property generated="never" lazy="false" name="username" type="java.lang.String"> <column length="20" name="USERNAME" not-null="true"/> </property> <property generated="never" lazy="false" name="password" type="java.lang.String"> <column length="15" name="PASSWORD"/> </property> <property generated="never" lazy="false" name="groups" type="java.lang.String"> <column length="20" name="GROUPS"/> </property> <property generated="never" lazy="false" name="email" type="java.lang.String"> <column length="48" name="EMAIL"/> </property> <property generated="never" lazy="false" name="status" type="java.lang.String"> <column length="1" name="STATUS"/> </property> <property generated="never" lazy="false" name="lastlogintime" type="java.lang.String"> <column length="23" name="LASTLOGINTIME"/> </property> <property generated="never" lazy="false" name="failcount" type="java.math.BigDecimal"> <column name="FAILCOUNT" precision="22" scale="0"/> </property> <property generated="never" lazy="false" name="locktime" type="java.lang.String"> <column length="23" name="LOCKTIME"/> </property> </class> <query name="query_user_by_username">from UserInfo U where U.username = ?</query> </hibernate-mapping>
然后,在Service中通过定义一个变量引用query中的name即可.
private static final String QUERY_USER_BYNAME = "query_user_by_username"; public List<UserInfo> queryUserByName(String name) { // TODO Auto-generated method stub List<UserInfo> list = new ArrayList<UserInfo>(); try { list = userDao.queryUserByName(QUERY_USER_BYNAME, name); } catch (DatabaseException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("查询出现异常!"); } return list; }
UserDao中的方法如下:
public List<UserInfo> queryUserByName(String queryName,Objcect...objects) throws DatabaseException { Query query = getSession().getNamedQuery(queryName); if(objects!=null && objects.length > 0 ){ for(int i = 0 ;i<objects.length;i++){ query.setParameter(i, objects[i]); } } return query.list(); }