Mybatis 第一个Demo

慕课网Mybatis  自动回复机器人

项目结构  以及表结构:



第一步.导入相应的Mybatis包放在web-app的lib文件夹下并加入路径

第二步.创建实体类Message

package Com.Entity;

public class Message {
	//主键
   private int id;
   //指令
   private String command;
   //描述
   private String description;
   //内容
   private String content;
   
   public Message(){
	   
   }
public int getId() {
	return id;
}
public void setId(int 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;
}
   
}

第三步.创建核心配置文件(把数据库的信息配置进核心文件)Configuration.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
<!-- 
  <settings>
    <setting name="useGeneratedKeys" value="false"/>
    <setting name="useColumnLabel" value="true"/>
  </settings>

  <typeAliases>
    <typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/>
  </typeAliases>
 -->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC">
        <property name="" value=""/>
      </transactionManager>
      <dataSource type="UNPOOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
      </dataSource>
    </environment>
  </environments>
<!-- 配置Message.xml文件 -->
  <mappers>
    <mapper resource="Com/config/sqlxml/Message.xml"/>
  </mappers>
 
</configuration>


第四步.实现db层(和数据库交互的类)

package Com.DB;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;



/**
 * 正真和数据库交互:db层
 * 编写访问数据库类
 * @author liu
 *
 */
public class DBAccess {
	//把异常向上抛,抛给DAO层  因为Dao层捕获异常,拿到SqlSession在finally中关闭SqlSession这个对象
   public  SqlSession getSqlSession() throws IOException{
	   //1.通过配置文件获取配置信息 是一个路径就不能写点了   从src下开始
	 Reader reader=Resources.getResourceAsReader("Com/config/Configuration.xml");
	 //2.通过配置信息创建一个sqlSesisonFactory
	  SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
	  //3.通过sqlSesisonFactory打开一个sqlSession
	  SqlSession sqlSession=sqlSessionFactory.openSession();
	return sqlSession;
   }
}

第五步.配置Message.xml文件(相当于JDBC中的写sql语句和查询结果的赋值给Message对象)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- 配置好了字段和属性,sql语句等  要把这个配置文件注册到核心配置文件Configuration.xml中 -->
<mapper namespace="Message">

  <resultMap type="Com.Entity.Message" id="MessageResult">
  <!-- 
      id:是主键名   result:是普通字段的名字
  column指的是数据库里面的字段  property指的是实体类中的属性
    数据库里面的字段类型与jdbcType里面的字段类型有一种对应关系
    jdbc      jdbcType
    int       INTEGER
    varchar   VARCHAR
  -->
    <id column="ID" jdbcType="INTEGER" property="id"/>
    <result column="COMMAND" jdbcType="VARCHAR" property="command"/>
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
    <result column="CONTENT" jdbcType="VARCHAR" property="content"/>
  </resultMap>
<!-- id为这个sql语句起一个唯一的名字(是在所有的配置文件中不能重名  ,以后不只一个配置文件)  
                     记住是唯一的 以后的sql语句不能重名  但是在不同的<mapper namespace="">中
                     相同的ID是可以存在的
                     sql语句的resultMap属性是指向resultMap标签的  所以resultMap标签的id就是sql语句resultMap属性的值
                     -->
  <select id="selectbycommand"  resultMap="MessageResult">
    SELECT ID,COMMAND,DESCRIPTION,CONTENT FROM message where 1=1
  </select>
 
</mapper>


第六步..编写Dao层

package Com.DAO;

import java.io.IOException;
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 org.apache.ibatis.session.SqlSession;

import Com.DB.DBAccess;
import Com.Entity.Message;
       /*
        * 和Message表相关的处理类
        */
public class Service {
	
	//返回的是符合条件的Message集合--》 Mybatis版
	public List<Message> selectbycommand(String command,String description){
		DBAccess dbAccess=new DBAccess();
		List<Message>  messagelist=new ArrayList<Message>();
		//sqlSession放在外面 无论如何都可以关掉
		SqlSession sqlSession=null;
	 //处理DB层抛上来的异常
		try{
			sqlSession=dbAccess.getSqlSession();
			//调用Message.xml文件中得sql语句获取返回结果并把每个message对象添加到messagelist中
			messagelist=sqlSession.selectList("Message.selectbycommand");
		}
		catch(IOException ex){
			ex.printStackTrace();
		}
		finally{
			if(sqlSession!=null){
				sqlSession.close();
			}
		}
		return messagelist;
	}
	
	
	
	//返回的是符合条件的Message集合--》 JDBC版
	/*public List<Message> selectbycommand(String command,String description){
	    List<Message>  messagelist=new ArrayList<Message>();
	 try {
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF8","root","123456");
		
	
	List<String> paramlist =new ArrayList<String>();
	
		StringBuffer sql=new StringBuffer("SELECT ID,COMMAND,DESCRIPTION,CONTENT FROM message where 1=1");
		if(command!=null&&!"".equals(command.trim())){
			//前面有空格或者sql字符串末尾加空格不然会报错
			sql.append(" and COMMAND=? ");
			paramlist.add(command);

			
		}
		if(description!=null&&!"".equals(description.trim())){
			sql.append(" and DESCRIPTION like '%' ? '%'");
			
			paramlist.add(description);
		}
	    PreparedStatement ptmt=	conn.prepareStatement(sql.toString());
	    for(int i=0;i<paramlist.size();i++){
	     ptmt.setString(i+1, paramlist.get(i));
	     
	     System.out.println("加入的字符串:"+paramlist.get(i));
	    }
	    
	   
	    Message mess=null;
	   ResultSet rs= ptmt.executeQuery();
	   while(rs.next()){
		   mess=new Message();
		   mess.setId(rs.getInt("ID"));
		   mess.setCommand(rs.getString("COMMAND"));
		   mess.setDescription(rs.getString("DESCRIPTION"));
		   mess.setContent(rs.getString("CONTENT"));
		   messagelist.add(mess);
	   }
	 	
	 
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	 return messagelist;
 }*/
}
            
	
第七步.编写Servlet并配置进web.xml文件

package Com.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Com.DAO.Service;
import Com.Entity.Message;

public class ListServlet extends HttpServlet {

	/**列表页面初始化控制
	 * The doGet method of the servlet. <br>
	 */
	 public List<Message>  messagelist=null;
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//接收页面的值
		String command=	request.getParameter("command");
		String description =request.getParameter("description");
		System.out.println("获取的参数:"+request.getParameter("command"));
		//向页面传值
		request.setAttribute("command",command);
		request.setAttribute("description",description);
		//查询消息列表并传递给页面
		Service service=new Service();
		messagelist=service.selectbycommand(command,description);
		//放入request中
	     request.setAttribute("messagelist", messagelist);
		   System.out.println("加入成功");
		//服务器内部转发request内保存的值就不会过期
		   
		   //跳转页面
	     request.getRequestDispatcher("/list.jsp").forward(request, response);
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}
   
}

<servlet-mapping>
    <servlet-name>ListServlet</servlet-name>
    <url-pattern>/List.action</url-pattern>
  </servlet-mapping>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

list.jsp文件

<%@ page language="java" import="java.util.*"
	contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<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="<%=basePath%>resource/css/all.css" rel="stylesheet"
	type="text/css" />
</head>
<body style="background: #e1e9eb;">
	<form action="<%=basePath%>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" οnclick="" />
								</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>

小结:

Model层:实体类

DB层(数据库层):加载驱动,获取链接
Dao层:执行SQL语句,获取操作结果封装消息,返回操作结果其中的操作就会用到Model层

Servlet:一般就是--》接收页面的值,向页面传值,查询消息列表(Dao层的操作结果)并返回给页面,向页面跳转

View层:接收Servlet的资源呈现给用户

各层之间如何耦合:如--》在Servlet层创建Dao层具体操作类的对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值