previous:MyBatis_2_MyBatis下載並搭建框架 next:MyBatis_4_一對多關系配置
---4-1 SQL動態拼接--------------------------------------------------------------
1.parameterType可直接填寫java.long包的類型,不需要包名
2. OGNL(與EL一樣是一種語言)功能強大的表達式語言(直接支持JAVA對象的代碼)。struts2也使用
"" 轉為""
&&轉為&&或者“and”
DAO
/** * 根據查詢條件查詢消息列表 */ public List<Message> queryMessageList(String command,String description) { DBAccess dbAccess = new DBAccess(); List<Message> messageList = new ArrayList<Message>(); SqlSession sqlSession = null; try { Message message = new Message(); message.setCommand(command); message.setDescription(description); sqlSession = dbAccess.getSqlSession(); // 通過sqlSession執行SQL語句 messageList = sqlSession.selectList("Message.queryMessageList", message); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(sqlSession != null) { sqlSession.close(); } } return messageList; }
1)#{變量名}//此處不是OGNL,是mybatis處理替換成“?”
2)where 1=1不需要
3)parameterType只接受一個parameter。
4)'%' #{description} '%'。注意#{description}前后空格必須。
調試使用log4j輔助。
<select id="queryMessageList" parameterType="com.imooc.bean.Message" resultMap="MessageResult">
select ID,COMMAND,DESCRIPTION,CONTENT from MESSAGE
<where>
<if test="command != null and !"".equals(command.trim())">
and COMMAND=#{command}
</if>
<if test="description != null and !"".equals(description.trim())">
and DESCRIPTION like '%' #{description} '%'
</if>
</where>
</select>
<select id="queryMessageList" parameterType="com.imooc.bean.Message" resultMap="MessageResult"> select ID,COMMAND,DESCRIPTION,CONTENT from MESSAGE <where> <if test="command != null and !"".equals(command.trim())"> and COMMAND=#{command} </if> <if test="description != null and !"".equals(description.trim())"> and DESCRIPTION like '%' #{description} '%' </if> </where> </select>
===LOG4J===========================
Log4j:日志輸出 。Jar包和配置文件(log4j.properties放入src根目錄下,(指定其他路徑時,需要配置))
MyBatistsjar包的logging.LogFactory.class源碼,定義了各種LOG的接口,其中包含Log4j,所以配置好Log4j 之后就可以打印LOG了
properties文件 key=value
//級別
logger log;
//級別由低到高
log.debug("adf");
log.info(message);
log.warn(message);
log.error(message);
//大於等於DEBUG級別的都輸出
log4j.rootLogger=DEBUG,Console//整個工程的級別//Console,輸出位置是控制台。DEBUG級別的原因:參照jar包的logging.jdbc下的類的源碼,比如ConnectionLogger.class的源碼里,是用debug()出力的,所以不能高於這個級別,否則不會打印Log。
log4j.appender.Console=org.apache.log4j.ConsoleAppender//配置此類才會輸出到控制台(log4j.rootLogger=DEBUG,A
log4j.appender.A)
log4j.appender.Console.layout=org.apache.log4j.PatternLayout//布局
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n//布局自定義
(%d [%t] %-5p [%c] - %m%n,%開頭的有特殊含義,[]空格-等都是原樣輸出。%d產生時間 %t所處線程名稱,%-5p:%p輸出的級別,-5表示輸出的字符至少占5位,不足用空格補齊,“-”表示補齊的空格在右邊,沒有“-”的話,空格就在左邊。%c輸出日志時的類全名+包名 %n換行%m輸出時附加的信息)
log4j.logger.org.apache=INFO//org.apache為包名,為org.apache包下配置為INFO級別
導入的包的源碼加入方法(如mybatis的源碼):
properties->Java Build Path->Libraries->mybatis包-Source attachment ...-edit-下載的源碼的根目錄層mybatis-3-mybatis-3.4.4-OK
===LOG4J==============================
---4-4 單條刪除--------------------------------------------------------------
Message.xml
<delete id="deleteOne" parameterType="int">
delete from MESSAGE where ID = #{_parameter}
</delete>
dao
/** * 單條刪除 */ public void deleteOne(int id) { DBAccess dbAccess = new DBAccess(); SqlSession sqlSession = null; try { sqlSession = dbAccess.getSqlSession(); // 通過sqlSession執行SQL語句 sqlSession.delete("Message.deleteOne", id); sqlSession.commit(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(sqlSession != null) { sqlSession.close(); } } }
sevice
package com.imooc.service; import java.util.ArrayList; import java.util.List; import com.imooc.dao.MessageDao; /** * 維護相關的業務功能 */ public class MaintainService { /** * 單條刪除 */ public void deleteOne(String id) { if(id != null && !"".equals(id.trim())) { MessageDao messageDao = new MessageDao(); messageDao.deleteOne(Integer.valueOf(id)); } } /** * 批量刪除 */ public void deleteBatch(String[] ids) { MessageDao messageDao = new MessageDao(); List<Integer> idList = new ArrayList<Integer>(); for(String id : ids) { idList.add(Integer.valueOf(id)); } messageDao.deleteBatch(idList); } }
Servlet
/** * 單條刪除控制層 */ @SuppressWarnings("serial") public class DeleteOneServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 設置編碼 req.setCharacterEncoding("UTF-8"); // 接受頁面的值 String id = req.getParameter("id"); MaintainService maintainService = new MaintainService(); maintainService.deleteOne(id); // 向頁面跳轉 req.getRequestDispatcher("/List.action").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
web.xml配置新增的servlet
<servlet> <servlet-name>ListServlet</servlet-name> <servlet-class>com.imooc.servlet.ListServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ListServlet</servlet-name> <url-pattern>/List.action</url-pattern> </servlet-mapping> <servlet> <servlet-name>DeleteOneServlet</servlet-name> <servlet-class>com.imooc.servlet.DeleteOneServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DeleteOneServlet</servlet-name> <url-pattern>/DeleteOneServlet.action</url-pattern> </servlet-mapping>
jsp:
get方式提交
<a href="${basePath}DeleteOneServlet.action?id=${message.id}">刪除</a>
<table class="tab2" width="100%"> <tbody> <tr> <th><input type="checkbox" id="all" onclick="#"/></th> <th>序號</th> <th>指令名稱</th> <th>描述</th> <th>操作</th> </tr> <c:forEach items="${messageList}" var="message" varStatus="status"> <tr <c:if test="${status.index % 2 != 0}">style='background-color:#ECF6EE;'</c:if>> <td><input type="checkbox" name="id" value="${message.id}"/></td> <td>${status.index + 1}</td> <td>${message.command}</td> <td>${message.description}</td> <td> <a href="#">修改</a> <a href="${basePath}DeleteOneServlet.action?id=${message.id}">刪除</a> </td> </tr> </c:forEach> </tbody> </table>
---4-5 批量刪除--------------------------------------------------------------
Message.xml
<delete id="deleteBatch" parameterType="java.util.List"> delete from MESSAGE where ID in( <foreach collection="list" item="item" separator=","> #{item} </foreach> ) </delete>
DAO:
/**
* 批量刪除
*/
public void deleteBatch(List<Integer> ids) {
DBAccess dbAccess = new DBAccess();
SqlSession sqlSession = null;
try {
sqlSession = dbAccess.getSqlSession();
// 通過sqlSession執行SQL語句
sqlSession.delete("Message.deleteBatch", ids);
sqlSession.commit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
}
service:
/**
* 批量刪除
*/
public void deleteBatch(String[] ids) {
MessageDao messageDao = new MessageDao();
List<Integer> idList = new ArrayList<Integer>();
for(String id : ids) {
idList.add(Integer.valueOf(id));
}
messageDao.deleteBatch(idList);
}
}
Servlet:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 設置編碼
req.setCharacterEncoding("UTF-8");
// 接受頁面的值
String[] ids = req.getParameterValues("id");
MaintainService maintainService = new MaintainService();
maintainService.deleteBatch(ids);
// 向頁面跳轉
req.getRequestDispatcher("/List.action").forward(req, resp);
}
JSP:
<script src="<%= basePath %>resources/js/common/jquery-1.8.0.min.js"></script>
<script src="<%= basePath %>resources/js/back/list.js"></script>
//通過JS,進行POST提交
<p class="g_title fix">內容列表 <a class="btn03" href="#">新 增</a> <a class="btn03" href="javascript:deleteBatch('<%=basePath%>');">刪 除</a></p>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="X-UA-Compatible"content="IE=9; IE=8; IE=7; IE=EDGE" /> <title>內容列表頁面</title> <link href="<%= basePath %>resources/css/all.css" rel="stylesheet" type="text/css" /> <script src="<%= basePath %>resources/js/common/jquery-1.8.0.min.js"></script> <script src="<%= basePath %>resources/js/back/list.js"></script> </head> <body style="background: #e1e9eb;"> <form action="<%= basePath %>List.action" id="mainForm" method="post"> <input type="hidden" name="currentPage" id="currentPage" value="${page.currentPage}"/> <div class="right"> <div class="current">當前位置:<a href="javascript:void(0)" style="color:#6E6E6E;">內容管理</a> > 內容列表</div> <div class="rightCont"> <p class="g_title fix">內容列表 <a class="btn03" href="#">新 增</a> <a class="btn03" href="javascript:deleteBatch('<%=basePath%>');">刪 除</a></p> <table class="tab1"> <tbody> <tr> <td width="90" align="right">指令名稱:</td> <td> <input name="command" type="text" class="allInput" value="${command}"/> </td> <td width="90" align="right">描述:</td> <td> <input name="description" type="text" class="allInput" value="${description}"/> </td> <td width="85" align="right"><input type="submit" class="tabSub" value="查 詢" /></td> </tr> </tbody> </table> <div class="zixun fix"> <table class="tab2" width="100%"> <tbody> <tr> <th><input type="checkbox" id="all" onclick="#"/></th> <th>序號</th> <th>指令名稱</th> <th>描述</th> <th>操作</th> </tr> <c:forEach items="${messageList}" var="message" varStatus="status"> <tr <c:if test="${status.index % 2 != 0}">style='background-color:#ECF6EE;'</c:if>> <td><input type="checkbox" name="id" value="${message.id}"/></td> <td>${status.index + 1}</td> <td>${message.command}</td> <td>${message.description}</td> <td> <a href="#">修改</a> <a href="${basePath}DeleteOneServlet.action?id=${message.id}">刪除</a> </td> </tr> </c:forEach> </tbody> </table> <div class='page fix'> 共 <b>${page.totalNumber}</b> 條 <c:if test="${page.currentPage != 1}"> <a href="javascript:changeCurrentPage('1')" class='first'>首頁</a> <a href="javascript:changeCurrentPage('${page.currentPage-1}')" class='pre'>上一頁</a> </c:if> 當前第<span>${page.currentPage}/${page.totalPage}</span>頁 <c:if test="${page.currentPage != page.totalPage}"> <a href="javascript:changeCurrentPage('${page.currentPage+1}')" class='next'>下一頁</a> <a href="javascript:changeCurrentPage('${page.totalPage}')" class='last'>末頁</a> </c:if> 跳至 <input id="currentPageText" type='text' value='${page.currentPage}' class='allInput w28' /> 頁 <a href="javascript:changeCurrentPage($('#currentPageText').val())" class='go'>GO</a> </div> </div> </div> </div> </form> </body> </html>
JS:通過submit()方法提交表單(post)
/**
* 調用后台批量刪除方法
*/
function deleteBatch(basePath) {
//設定action
$("#mainForm").attr("action",basePath + "DeleteBatchServlet.action");
$("#mainForm").submit();
}
---4-1 SQL動態拼接--------------------------------------------------------------
---4-1 SQL動態拼接--------------------------------------------------------------