【MyBatis學習】:通過自動回覆機器人學習MyBatis(一)
自動回覆機器人案例分析基本功能:
接收發送指令;
根據指令自動回覆對應的內容;
專案使用技術:
JSP+Servlet+JDBC
專案使用資料庫中的資料表message
專案目錄:
案例程式碼:
web.xml配置程式碼:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>mybatis_01</display-name> <servlet> <servlet-name>ListServlet</servlet-name> <servlet-class>com.demo.web.servlet.ListServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ListServlet</servlet-name> <url-pattern>/List.action</url-pattern> </servlet-mapping> </web-app>
list.jap程式碼:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <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="css/all.css" rel="stylesheet" type="text/css" /> </head> <body style="background: #e1e9eb;"> <form action="List.action" id="mainForm" method="post"> <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="#">刪 除</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" /></td> <td>${status.index + 1 }</td> <td>${message.command }</td> <td>${message.description }</td> <td> <a href="#">修改</a> <a href="#">刪除</a> </td> </tr> </c:forEach> </tbody> </table> <div class='page fix'> 共 <b>4</b> 條 <a href='###' class='first'>首頁</a> <a href='###' class='pre'>上一頁</a> 當前第<span>1/1</span>頁 <a href='###' class='next'>下一頁</a> <a href='###' class='last'>末頁</a> 跳至 <input type='text' value='1' class='allInput w28' /> 頁 <a href='###' class='go'>GO</a> </div> </div> </div> </div> </form> </body> </html>
ListServlet.java原始碼:
package com.demo.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.demo.service.ListService; /** * 列表頁面初始化控制 * @author Administrator * @date 2016年12月20日 */ @SuppressWarnings("serial") public class ListServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //設定編碼 req.setCharacterEncoding("UTF-8"); //從頁面獲取值 String command = req.getParameter("command"); String description = req.getParameter("description"); //向頁面傳值 req.setAttribute("command", command); req.setAttribute("description", description); //呼叫業務邏輯層 ListService listService = new ListService(); //向頁面傳值 req.setAttribute("messageList", listService.queryMessageList(command, description)); //跳轉 req.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
ListService.java原始碼:
package com.demo.service;
import java.util.List;
import com.demo.dao.MessageDao;
import com.demo.entity.Message;
/**
* 業務邏輯層
* @author Administrator
* @date 2016年12月20日
*/
public class ListService {
public List<Message> queryMessageList(String command, String description){
MessageDao messageDao = new MessageDao();
return messageDao.queryMessageList(command, description);
}
}
Message.java原始碼:
package com.demo.entity;
/**
* 實體類Message
* @author Administrator
* @date 2016年12月20日
*/
public class Message {
private String id;
private String command;
private String description;
private String content;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
ListDao.java原始碼:
package com.demo.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.demo.entity.Message;
/**
* 持久層
* @author Administrator
* @date 2016年12月20日
*/
public class MessageDao {
public List<Message> queryMessageList(String command, String description){
//資料庫連線
Connection connection = null;
//預編譯的statement,可以提高資料庫的效能
PreparedStatement statement = null;
//結果集
ResultSet rs = null;
List<Message> messageList = new ArrayList<Message>();
try {
//1、註冊驅動
Class.forName("com.mysql.jdbc.Driver");
//2、通過驅動管理類獲取資料庫的連線
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/imooc","root","root");
//3、建立sql語句
StringBuilder sql = new StringBuilder("select ID,COMMAND,DESCRIPTION,CONTENT from MESSAGE where 1 = 1");
List<String> paramList = new ArrayList<String>();
if (command != null && !"".equals(command.trim())) {
sql.append(" and COMMAND = ?");
paramList.add(command);
}
if (description != null && !"".equals(description.trim())) {
sql.append(" and DESCRIPTION like '%' ? '%'");
paramList.add(description);
}
//向資料庫發起要求,獲取預處理的statement
statement = connection.prepareStatement(sql.toString());
//設定引數
for (int i = 0; i < paramList.size(); i++) {
statement.setString(i + 1, paramList.get(i));
}
//4、向資料庫發出SQL語句查詢,獲取結果集
rs = statement.executeQuery();
//5、處理結果集
while (rs.next()) {
Message message = new Message();
messageList.add(message);
message.setId(rs.getString("ID"));
message.setCommand(rs.getString("COMMAND"));
message.setDescription(rs.getString("DESCRIPTION"));
message.setContent(rs.getString("CONTENT"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
//6、釋放資源
if(rs !=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//返回List結果集
return messageList;
}
}
演示效果:
開啟顯示列表頁
進行兩個條件的模糊查詢:
進行一個條件的模糊查詢
這只是完成了一個模糊查詢的功能,最重要的就是持久層(dao層)的原始的JDBC程式碼,這是持久層框架需要
解決的一層,不管是Hibernate還是MyBatis,都需要對原始JDBC程式碼進行封裝,以便獲得更簡潔高效的程式碼。
對原生態JDBC程式(單獨使用JDBC)中問題總結
1)資料庫連線,使用時就建立,不使用立即釋放,對資料庫進行頻繁的連線開啟和關閉,造成資料庫資源浪費,
影響資料庫效能。
解決方案:使用資料庫連線池來管理資料庫連線。
2)將SQL語句硬編碼到Java程式碼中,如果SQL語句修改,需要重新編譯Java程式碼,不利於系統維護。
解決方案:將SQL語句配置在XML配置檔案中,即使SQL變化,不需要對Java程式碼進行重新編譯。
3)向prepareStatement中設定引數,對佔位符位置和設定引數值,硬編碼在Java程式碼中,不利於系統維護。
解決方案:將SQL語句及佔位符和引數全部配置到XML中。
4)從resultSet中遍歷結果集資料時,存在硬編碼,將獲取表的欄位進行硬編碼,不利於系統維護。
解決方案:將查詢的結果集,自動對映成Java物件。