public List findByDeviceIdsRasId(final String rasId, final List deviceIds)
throws DataAccessException
{
if (StringUtils.isEmpty(rasId) || CollectionUtils.isEmpty(deviceIds))
{
return null;
}
/*return getHibernateTemplate().execute(new HibernateCallback>()
{
@Override
public List<RasPo> doInHibernate(Session session) throws HibernateException,
SQLException
{
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("(");
for (String deviceId : deviceIds)
{
stringBuffer.append("'").append(deviceId).append("'").append(",");
}
String str = stringBuffer.substring(0, stringBuffer.length() - 1);
str = str + ")";
Query query= session.createQuery("from RasPo where rasId='" + rasId + "' and deviceId in " + str);
List<RasPo> list = query.list();
return list;
}
});*/
List<RasPo> list=null;
try{
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("(");
for (String deviceId : deviceIds)
{
stringBuffer.append("'").append(deviceId).append("'").append(",");
}
String str = stringBuffer.substring(0, stringBuffer.length() - 1);
str = str + ")";
list = getHibernateTemplate().find("from RasPo where rasId=? and deviceId in ?",
new String[] {rasId, str});
}
catch (DataAccessException e)
{
throw e;
}
return list;
}
使用上面的注释的可以查询出来,但是改为find()方法后就查询不出来了。我感觉着没有什么区别了。求解
ist = getHibernateTemplate().find("from RasPo where rasId=? and deviceId in ?",
new String[] {rasId, str});
第二个?是 in 不能传 一个字符串,解决方案,类似于下边:
List result = getHibernateTemplate().executeFind(new HibernateCallback>() {
@Override
public List doInHibernate(Session session) throws HibernateException, SQLException {
String hql = "from SampleModel where uuid in (:uuids)";
Query q = session.createQuery(hql);
q.setParameterList("uuids", new Object[]{0, 1});
return q.list();
}
});
1、hql使用 String hql = "from SampleModel where uuid in (:uuids)"; 在hibernate必须使用命名参数;
2、赋值 q.setParameterList("uuids", new Object[]{0, 1}); 可以是集合/数组;
hibernate会动态生成如下语句(in里边多个?)
Hibernate: select samplemode0_.uuid as uuid0_, samplemode0_.name as name0_ from tbl_sample samplemode0_ where samplemode0_.uuid in (? , ?)
如下是不支持的
list = getHibernateTemplate().find("from RasPo where rasId=? and deviceId in ?",
new String[] {rasId, str});
你的也应该改成类似于这样
hql = "from RasPo where rasId=:rasId and deviceId in (:deviceIds)";
设置参数
不能传str 而是一个deviceIds集合
[code="java"]list = getHibernateTemplate().find("from RasPo where rasId=? and deviceId in ?",
new String[] {rasId, str}); [/code]
你先改成这样的 应该可以:
[code="java"]
list = getHibernateTemplate().find("from RasPo where rasId='" + rasId + "' and deviceId in " + str); [/code]
@jinnianshilongnian
哥们说的对。in 操作要么传入一个集合
要么传入一个字符串
但这个字符有特殊要求
规范写法是这样的:
from RasPo where rasId=? and deviceId in (?)
传入参数是:
from RasPo where rasId=? and deviceId in (1,2,3,3,5)