//对参数拼接sql的时候,//replaceAll("'","''")即可.即把单引号替换成双单引号
public List<Device> findDeviceUsers(final String devMac,final String serviceId){ return getHibernateTemplate().execute(new HibernateCallback<List<Device>>() { @Override public List<Device> doInHibernate(Session session) throws HibernateException, SQLException { List<Device> deviceList = null; String HQL = " from Device d,UsersToDevice ut "; String where = " where 1=1"; if (!serviceId.isEmpty()&&serviceId!=null){ // String HQL = " from Device d,Users u,UsersToDevice ut where d.devMac='"+devMac+"' and d.serviceId='"+serviceId+"' and ut.openid='"+openId+"'"; where +=" and d.serviceId='"+serviceId.replaceAll("'","''")+"'"; } if (!devMac.isEmpty() && devMac!=null){ where +=" and d.devMac='"+devMac.replaceAll("'","''")+"'"; } where+=" and d.id=ut.id"; HQL+=where; Query query = session.createQuery(HQL); List<Object[]> resultList = query.list(); if (resultList!=null && !resultList.isEmpty()){ deviceList = new ArrayList<Device>(resultList.size()); for (Object[] objects : resultList) { Device device = (Device)objects[0]; deviceList.add(device); } } return deviceList; } }); }