项目是ssh框架的。
spring把事务切在了service层。
当我在action中通过service层某个类(pdQuestionInfoServiceImpl)查询了一个对象,
然后对该对象的属性进行了修改,并返回给前台jsp使用。
结果发现被修改后的属性值更新到了数据库中。
明明把事务且在了service,为何action中会这样呢?
是不是有哪步调用了更新数据库的
@Action("search1")
public String querySearchResult1(){
try {
String basePath = getBasePath();
log.info("basePath : " + basePath);
List<PdQuestionInfo> tempList = new ArrayList<PdQuestionInfo>();
PdQuestionInfo test2 = new PdQuestionInfo();
test2.setId(172);
tempList.add(test2);
PdQuestionInfo test = new PdQuestionInfo();
test.setId(171);
tempList.add(test);
PdQuestionInfo test3 = new PdQuestionInfo();
test3.setId(173);
tempList.add(test3);
pdQuestionInfoList = new ArrayList<PdQuestionInfo>(tempList.size());
for(PdQuestionInfo temp : tempList){
temp = pdQuestionInfoServiceImpl.getInfoById(temp.getId());
if(null != temp){
temp.setAnswer(Tools.replaceImgSrc(temp.getAnswer(), basePath));
temp.setContent(Tools.replaceImgSrc(temp.getContent(), basePath));
pdQuestionInfoList.add(temp);
}
}
success = true;
msg = "操作成功!";
} catch (Exception e) {
success = false;
msg = "没有搜索到相关的作业题!";
log.info(msg);
}
return JSON;
}
代码如上,结果发现,
当tempList只有一条数据时,正常。
当tempList多余一条数据时,除最后一条数据不会被更新到数据库,其他记录都会被更新.
解决办法:查询操作以非实物的方式运行。
现象产生原因:
因为hibernate查询出的对象都是代理对象,所以改动都会被记录,
而你for循环在同一个线程中,所以你在action中的改动,hibernate是能记住的,
在你继续调用查询方法的时候会开启事务,那么for循环的前一次修改就会被提交。
希望能帮到你...