疏忽下BeanUtils.copyProperties()引发的问题

昨天在Action中完成某一个更新功能的时候总是无法更新成功,而且什么错误都不报。经过仔细而又认真的再三查找,终于被我找到问题所在了。

先来说说查错过程。首先从更新失败与不报任何错误来看,我们的代码肯定是没有错的,错误应该是出在DAO层的SQL语句中。经查证,SQL语句也是正确的。给出SQL语句具体来看看。

String sql = "UPDATE tb_member SET name=?,password=?,reallyName=?,age=?,profession=?,email=?,question=?,result=? WHERE id=? ";
boolean ok = false;
try {
conn = DB.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, mbr.getMbrName());
pstmt.setString(2, mbr.getMbrPassword());
pstmt.setString(3, mbr.getMbrReallyName());
pstmt.setInt(4, mbr.getAge());
pstmt.setString(5, mbr.getMbrProfession());
pstmt.setString(6, mbr.getMbrEmail());
pstmt.setString(7, mbr.getMbrQuestion());
pstmt.setString(8, mbr.getMbrResult());
pstmt.setInt(9, mbr.getMbrId());
int i = pstmt.executeUpdate();
if(i > 0){
ok = true;
}

如上SQL语句,可以看到它是一个带更新条件的SQL语句(废话啊⊙﹏⊙b),那么在什么情况下这条语句可以正常执行而又返回的更新行数i又小于或等于0呢?答案就是,这里id的值在这张表中并不存在!

从上面的代码可以看到,这里的id是由pstmt.setInt(9, mbr.getMbrId())来赋值的。使用System.out.println(mbr.getMbrId())打印输出得到结果为0,其他属性值都存在。那就是说我们可能在Action中对mbr进行赋值时忘记了id属性。再检查一下Action中的方法。

public ActionForward doUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception{
MemberForm memberForm = (MemberForm) form;// TODO Auto-generated method stub
HttpSession session = request.getSession();
String forwardName = "failure";
//获得当前会员信息
Member mbr = (Member)session.getAttribute("member");
//判断是否已经登录
if(mbr != null){
//赋值
BeanUtils.copyProperties(mbr, memberForm);
//更新会员信息
if(mbrBiz.updateMember(mbr)){
forwardName = "success";
}
}
return mapping.findForward(forwardName);
}

打眼一看好像也没错啊!起初我也认为绝对没错,我还以为是Tomcat的问题呢。后来仔细琢磨了一下BeanUtils.copyProperties(mbr, memberForm)这行代码。memberForm是前端控制器ActionServlet自动填充的,它封装了JSP页面中的表单数据。我使用BeanUtils.copyProperties()将memberForm中的各属性值逐一赋给mbr中的各个属性。这时我才突然明白了,我的JSP页面的表单中并不存在id这一数据!我将memberForm的id属性打印出来为null,由于BeanUtils.copyProperties()的内部实现机制的问题,这里它自动将mbr的id属性改为了0,于是就造成了更新不成功也不报错的结果。

那么,该怎么改好呢?很简单!在使用BeanUtils.copyProperties()方法之前先执行一下memberForm.setMbrId(mbr.getMbrId())即可。如此简单的一个问题花了我半个多小时,再加上分析整理写出来就更多了,O(∩_∩)O哈哈~。


除非另有声明,本站遵循【署名-非商业性使用-相同方式共享 3.0 共享协议】授权。

转载原创文章请注明,转载自:Neeke[http://www.ineeke.com]

本文链接: http://www.ineeke.com/archives/beanutilscopyproperties/

2009年1月3日 | 归档于 J2EE技术 | 1 条评论
标签: ,
  1. 2009年1月3日 17:32 | #1

    你们培训班什么时候才放假 还在上课

    Gravatar头像neeke 于 2009-1-4 15:18:58 回复

    18号左右放假吧。

发表评论

XHTML: 您可以使用这些标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">
n:-zy n:-zr n:-zan n:-xf n:-wx n:-tz n:-tt n:-ts n:-sy n:-st n:-ss n:-sk n:-qd n:-pz n:-lh n:-kun n:-ku n:-hx n:-hd n:-gt n:-gg n:-bz

NOTICE: You should type some Chinese word (like “你好”) in your comment to pass the spam-check, thanks for your patience!