hibernate 返回新插入数据的Id

时间:2022-06-23 06:32:57

例如 表明 studentInfo

String sql="set set nocount on studentInfo(列名,列名) values('值','值');select @@identity as inserId";

  

java代码:

public int executeCount(String sql, Map<String, Object> paramMap) {
Session session = sessionFactory.getCurrentSession();
Query query = session.createSQLQuery(sql);
if (paramMap != null && paramMap.size() > 0) {
for (Entry<String, Object> entry : paramMap.entrySet()) {
Object value = entry.getValue();
if (value != null && value.getClass().isArray()) {
query.setParameterList(entry.getKey(),
Arrays.asList((Object[]) value));
continue;
}
query.setParameter(entry.getKey(), entry.getValue());
}
}
List<?> list = query.list();
if (list != null && list.size() > 0) {
if(list.get(0)!=null){
return Integer.parseInt(list.get(0).toString());
}
}
return 0;
}

  在dao层调用

this.executeCount(sql, map);

  注:map 放的是添加的值