关于struts2+ibatis多对象批量更新的兑现及影响行数的返回
关于struts2+ibatis多对象批量更新的实现及影响行数的返回
项目中可能会涉及到,多条记录的增加。我们一般会多个form使用js提交的方式,或者多个form多次提交的方式。这里谈一点自己在项目中应用到的实例解决方案。涉及到struts+ibatis,freemarker表示页面。
操作对象Model:Test.java
form表单。如:test.ftl
struts的Action:TestAction.java
Struts的配置:struts.xml
ibatis的sqlmap配置:sqlmap-config.xml,这里假设有表test(name,nameUrl)
注意,这里的插入没有使用ibatis的insert而是update操作,是因为批量更新的时候insert无法返回影响的条数,所以使用了update方法。这里大家有更好的方法欢迎共享
项目中可能会涉及到,多条记录的增加。我们一般会多个form使用js提交的方式,或者多个form多次提交的方式。这里谈一点自己在项目中应用到的实例解决方案。涉及到struts+ibatis,freemarker表示页面。
操作对象Model:Test.java
class Test{ String name; String nameUrl; set...() get...() }
form表单。如:test.ftl
<form name="addInfo" action="test.action" method="post" onsubmit="return checkForm();"> <table width="99%" border="0" align="center" cellpadding="3" cellspacing="1"> <tr> <td width="100%" colspan="2">添加</td> </tr> <tr> <td width="15%" height="24" align="right">标题1:</td> <td width="85%"> <input type="text" name="listTest[0].name" id="name0" value="" size="60" maxlength="40" /> </td> </tr> <tr> <td width="15%" height="24" align="right">链接1:</td> <td width="85%"> <input type="text" name="listTest[0].nameUrl" id="nameUrl0" value=" /> </td> </tr> <tr> <td width="15%" height="24" align="right">标题2:</td> <td width="85%"> <input type="text" name="listTest[1].name" id="name1" value="" size="60" maxlength="40" /> </td> </tr> <tr> <td width="15%" height="24" align="right">链接2:</td> <td width="85%"> <input type="text" name="listTest[1].nameUrl" id="nameUrl1" value=" /> </td> </tr> <tr> <td width="15%" height="24"> </td> <td width="85%"><input type="submit" value="保存" id="saveImg" /> <input type="reset" value="取消" name="" /></td> </tr> </table> </form>
struts的Action:TestAction.java
class TestAction extends ActionSupport{ List<Test> listTest; public String test() throws Exception{ //调用service保存(Dao的insertListTest方法) } setListTest... getListTest... }
Struts的配置:struts.xml
<action name="test" class="包路径.TestAction" method="test"> <result name="success" type="freemarker">/success.ftl</result> <result name="error" type="freemarker">/error.ftl</result> </action>
ibatis的sqlmap配置:sqlmap-config.xml,这里假设有表test(name,nameUrl)
<update id="insertListTest" parameterClass="java.util.List"> INSERT INTO test(name,nameUrl) VALUES <iterate conjunction=","> (#value[].name#,#value[].nameUrl#) </iterate> </update>
注意,这里的插入没有使用ibatis的insert而是update操作,是因为批量更新的时候insert无法返回影响的条数,所以使用了update方法。这里大家有更好的方法欢迎共享