记一次MyBatis试手项目
▲我踩的坑▲
一.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
artifactId一开始写成了servlet-api 这样子是下载不到新版本的
二.
mybatis.xml中url:
url=jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai
增加?serverTimezone=Asia/Shanghai的原因:
当JDBC与Mysql服务器建立连接时,如果我们没有给JDBC指定时区,JDBC就会取Mysql服务器的默认时区,也就是CST,而它又把CST理解成了美国中部时间,结果就使用了美国中部时间的时区,而不是后端系统服务器的时区。
- 解决办法
- 设置Tidb服务器的时区为我们想要的时区,比如UTC+00,或者UTC+08;
- 重新配置后端系统连接数据库服务器的URL,添加参数serverTimezone=Asia/Shanghai
- 总结
在和数据库打交道的时候一定要注意时区问题,尤其是针对涉及国际化的业务来说,各个服务器的时区可能有很大差异,如果不显示的指定统一的时区,很容易导致混乱。
三.
步骤
创建项目
pom.xml中添加
war //一旦开始部署就是已war包的形式部署观察项目结构
java源代码 resources配置文件
新建webapp文件夹(存放页面)→WEB-INF→web.xml(项目的配置文件)
随便找一个其他项目web.xml复制到该项目的web.xml即可,且修改项目名称
创建项目主页index.jsp
先进行测试(project structure中加入web Arfifacts)//deploy能同步信息
引入bootstrap和jQuery(导入到webapp\lib)
<link rel="stylesheet" href="lib/bootstrap-3.3.7/dist/css/bootstrap.min.css"> <script src="lib/2.2.4/jquery-1.12.4.min.js"></script> <script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
创建结果如下:
5.创建数据库xiaoben→表:thing
CREATE TABLE thing(
id INT AUTO_INCREMENT PRIMARY KEY COMMENT '记录编号',
me VARCHAR(20) NOT NULL COMMENT '记录人物',
others VARCHAR(20) NOT NULL COMMENT '相关对象',
gob VARCHAR(100) COMMENT '事情好坏',
Rtime DATETIME COMMENT '记录时间',
Dtime VARCHAR(40) COMMENT '代办时间',
place VARCHAR(100) COMMENT '发生地点',
content VARCHAR(1000) COMMENT '内容'
) DEFAULT CHARSET "utf8";
6.pom.xml中增加依赖
mybatis和mysql连接驱动
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency> </dependencies>
7.增加mybatis配置文件
resources中创建mybatis-config.xml → 从mybatis官方文档中复制结构(ctrl+alt+l可以格式化代码)→
创建db.properties(以value形式存在,且在mybatis-config.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>
<properties resource="db.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/usersMapper.xml"/>
</mappers>
<!--这是mybatis官方文档给的结构-->
</configuration>
db.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai
username=root
password=mjj666123
- 创建映射配置文件(resources/mapper/userMapper.xml)
参考官方文档复制
<?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">
<!--
mapper 用于定义一个映射配置文件的根节点
namespace属性是用来配置命名空间,主要进行session级别的缓存管理
命名空间默认情况下,使用我们当前操作的实体类的全路径
-->
<mapper namespace="com.mjj.entity.thing">
</mapper>
创建实体类(java/com.mjj.entity/thing)
package com.mjj.entity; import java.util.Date; public class thing { private Integer id;//事件编号 private String me;//主人 private String others;//被记录人 private String gob;//事件好坏 private Date Rtime;//创建时间 private String Dtime;//代办时间 private String place;//发生地点 private String content;//详细内容 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getMe() { return me; } public void setMe(String me) { this.me = me; } public String getOthers() { return others; } public void setOthers(String others) { this.others = others; } public String getGob() { return gob; } public void setGob(String gob) { this.gob = gob; } public Date getRtime() { return Rtime; } public void setRtime(Date rtime) { Rtime = rtime; } public String getDtime() { return Dtime; } public void setDtime(String dtime) { Dtime = dtime; } public String getPlace() { return place; } public void setPlace(String place) { this.place = place; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
然后再uesrMapper.xml中的namespace添加实体类的路径如下
<mapper namespace="com.mjj.entity.thing">
</mapper>
- 主配置文件引入映射文件
<mappers>
<mapper resource="mapper/usersMapper.xml"/>
</mappers>
resource:mybatis-config.xml
InputStream
SqlSessionFactory
SqlSession
执行我们的配置好的SQL语句
- 创建(com.mjj.utils/SqlSessionFactoryUtils)
package com.mjj.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
public class SqlSessionFactoryUtils {
private static String RESOURCE="mybatis-config.xml";
private static SqlSessionFactory sqlSessionFactory;
private static ThreadLocal<SqlSession> threadLocal=new ThreadLocal<SqlSession>();
/*
* 创建一个初始化SqlSessionFactory方法
* */
public static void initSqlSessionFactory(){
try {
InputStream inputStream= Resources.getResourceAsStream(RESOURCE);
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* 获取工厂对象的方法
*
* */
public SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
// 关闭SqlSession的方法
public static void close(){
SqlSession session=threadLocal.get();
if(session!=null){
session.close();
threadLocal.set(null);
}
}
}
- 创建(com.mjj.listener/InitSqlSessionListener.java)
package com.mjj.listener;
import com.mjj.utils.SqlSessionFactoryUtils;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class InitSqlSessionListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("容器加载中");
//初始化我们的SqlSessionFactory对象
SqlSessionFactoryUtils.initSqlSessionFactory();
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("容器销毁中");
//关闭SqlSession对象
SqlSessionFactoryUtils.close();
}
}
14.创建(com.mjj.dao/thingDao)
package com.mjj.dao;
import com.mjj.entity.thing;
import com.mjj.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
public class thingDao {
private SqlSession sqlSession= SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
private List<thing> list;
public List<thing> findAll(){
try {
list=sqlSession.selectList("findAll");
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return list;
}
}
关于findAll配置,在resources/mapper/usersMapper.xml中进行配置
select标签中进行配置
<?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">
<mapper namespace="com.mjj.entity.thing">
<select id="findAll" resultType="com.mjj.entity.thing">
select * from thing
</select>
</mapper>
- 引入jstl
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
16.创建Servlet/NoteFindServlet
package servlet;
import Dao.thingDao;
import entity.thing;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/index")
public class NoteFindServlet extends HttpServlet {
private thingDao thDao= new thingDao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<thing> list=thDao.findAll();
req.setAttribute("thingList",list);
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
创建home.jsp 将请求转发至index.jsp 同时修改web.xml的
<%-- Created by IntelliJ IDEA. User: Lenovo Date: 2019/8/11 Time: 11:47 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% response.sendRedirect("index"); %> </body> </html>
对index.jsp进行修改
- 引入jstl标签以及依赖
- foreach循环
<%-- Created by IntelliJ IDEA. User: Lenovo Date: 2019/8/7 Time: 12:15 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>马嘉骏的小本本</title> <link rel="stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <script src="lib/2.2.4/jquery-1.12.4.min.js"></script> <script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="page-header"> <h1><span class="glyphicon glyphicon-heart"></span> 马嘉骏的小本本 <small> 记录每件事</small></h1> </div> </div> <div class="row"> <div class="jumbotron"> <h1>记录点滴</h1> <p>当他回首往事的时候,他不会因为虚度年华而悔恨,也不会因为碌碌无为而羞耻</p> <p><a class="btn btn-primary btn-lg" href="#" role="button">获取更多</a></p> </div> </div> <div class="row"> <table class="table table-hover table-striped"> <tr> <th>记录编号</th> <th>记录人物</th> <th>相关对象</th> <th>事物好坏</th> <th>记录时间</th> <th>代办时间</th> <th>发生地点</th> <th>详细内容</th> <th>操作</th> </tr> <c:forEach var="thing" items="${thingList}"> <tr> <td>${thing.id}</td> <td>${thing.me}</td> <td>${thing.others}</td> <td>${thing.gob}</td> <td>${thing.rtime}</td> <td>${thing.dotime}</td> <td>${thing.place}</td> <td>${thing.content}</td> <td> <a href="">查看</a> <a href="">修改</a> <a href="">删除</a> </td> </tr> </c:forEach> </table> </div> </div> </body> </html>
这边要特别注意一下 :在json形式传回的数据 中 类中的属性首字母是默认小写的 (即使在类中属性的首个字母是大写 传过来都是小写的形式)
所以返回属性必须全部是小写 如${thing.rtime}
接下来就是查询阶段的编写
- thingDao中添加findById
package Dao;
import utils.SqlSessionFactoryUtils;
import entity.thing;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class thingDao {
private SqlSession sqlSession;
private List<thing> list;
private thing thi;
private SqlSession getSession(){
sqlSession= SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
return sqlSession;
}
public List<thing> findAll(){
try {
list=getSession().selectList("findAll");
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return list;
}
//添加部分
public thing findById(Integer id){
try {
thi=getSession().selectOne("findById", id);
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return thi;
}
}
- usersMapper.xml中添加findById的sql语句
<select id="findById" resultType="entity.thing">
select * from thing where id=#{id}
</select>
- 创建Servlet/thingFindServlet.java
package servlet;
import Dao.thingDao;
import entity.thing;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/index")
public class NoteFindServlet extends HttpServlet {
private thingDao thDao= new thingDao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<thing> list=thDao.findAll();
req.setAttribute("thingList",list);
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
- 查看页面的编写detail.jsp
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: Lenovo
Date: 2019/8/14
Time: 15:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>马嘉骏的小本本</title>
<link rel="stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
<script src="lib/2.2.4/jquery-1.12.4.min.js"></script>
<script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="page-header">
<h1><span class="glyphicon glyphicon-heart"></span>
马嘉骏的小本本 <small> 记录每件事</small></h1>
</div>
</div>
<div class="row">
<div class="jumbotron">
<h1>记录点滴</h1>
<p>当他回首往事的时候,他不会因为虚度年华而悔恨,也不会因为碌碌无为而羞耻</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">获取更多</a></p>
</div>
</div>
<c:set var="thing" value="${thing}"></c:set>
<div class="row">
<div class="col-md-8 col col-md-offset-2">
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">记录编号</label>
<div class="col-sm-10">
<p class="form-control-static">${thing.id}</p>
</div>
</div>
<div class="form-group">
<label for="me" class="col-sm-2 control-label">记录人物</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="me" value="${thing.me}" name="me" placeholder="请输入记录人物">
</div>
</div>
<div class="form-group">
<label for="others" class="col-sm-2 control-label">相关对象</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="others" value="${thing.others}" name="others" placeholder="请输入相关对象">
</div>
</div>
<div class="form-group">
<label for="gob" class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="gob" value="${thing.gob}" name="gob" placeholder="请输入事情好坏">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">记录时间</label>
<div class="col-sm-10">
<p class="form-control-static">
<fmt:formatDate value="${thing.rtime}" ></fmt:formatDate>
</p>
</div>
</div>
<div class="form-group">
<label for="dotime" class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="dotime" value="${thing.dotime}" name="dotime" placeholder="请输入代办时间">
</div>
</div>
<div class="form-group">
<label for="place" class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="place" value="${thing.place}" name="place" placeholder="请输入事情发生地点">
</div>
</div>
<div class="form-group">
<label for="content" class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="content" value="${thing.content}" name="content" placeholder="请输入事情详细内容">
</div>
</div>
</form>
<div class="form-group">
<input type="submit" value="提交数据更新" class="btn btn-primary">
</div>
</div>
</div>
</div>
</body>
</html>
sql动态语句查询
usersMapper.xml
<?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"> <!-- mapper 用于定义一个映射配置文件的根节点 namespace属性是用来配置命名空间,主要进行session级别的缓存管理 命名空间默认情况下,使用我们当前操作的实体类的全路径 --> <mapper namespace="entity.thing"> <select id="findThing" resultType="entity.thing"> select * from thing <if test="id!=null"> where id=#{id} </if> </select> </mapper>
实体类中thing添加构造方法
public thing(){ } public thing(Integer id) { this.id = id; }
Dao中改变函数名,以及参数
package Dao; import utils.SqlSessionFactoryUtils; import entity.thing; import org.apache.ibatis.session.SqlSession; import java.util.List; public class thingDao { private SqlSession sqlSession; private List<thing> list; private thing thi; private SqlSession getSession(){ sqlSession= SqlSessionFactoryUtils.getSqlSessionFactory().openSession(); return sqlSession; } public List<thing> findAll(){ try { list=getSession().selectList("findThing"); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } return list; } public thing findById(Integer id){ try { thi=getSession().selectOne("findThing",new thing(id)); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } return thi; } }
自定义映射关系集合:主要包含对于一些自定义操作的配置,如不一致的属性和字段
usersMapper.xml(result配置,主要配置普通属性,column表示配置的是数据库字段名称 property配置的是实体类的属性名称)
<?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"> <!-- mapper 用于定义一个映射配置文件的根节点 namespace属性是用来配置命名空间,主要进行session级别的缓存管理 命名空间默认情况下,使用我们当前操作的实体类的全路径 --> <mapper namespace="entity.thing"> <!--<select id="findThing" resultType="entity.thing">--> <select id="findThing" resultMap="findthing"> select * from thing <if test="id!=null"> where id=#{id} </if> </select> <resultMap id="findthing" type="entity.thing"> <result column="me" property="wo"></result> </resultMap> </mapper>
log4j的使用
引入依赖
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
创建resources/log4j.properties
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n
在servlet中使用
private Logger log=loggger.getlogger(thingFindServlet.class);
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id=req.getParameter("id");
log.info("获取到查询参数id→→"+id);
thing thi= tDao.findById(Integer.parseInt(id));
log.info("查询数完成,查询到的数据:"+thi.toString());
req.setAttribute("thing",thi);
req.getRequestDispatcher("detail.jsp").forward(req,resp);
}
log.info便会在日志记录中输出
27.添加语句
userMapper
<?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">
<!--
mapper 用于定义一个映射配置文件的根节点
namespace属性是用来配置命名空间,主要进行session级别的缓存管理
命名空间默认情况下,使用我们当前操作的实体类的全路径
-->
<mapper namespace="entity.thing">
<!--<select id="findThing" resultType="entity.thing">-->
<select id="findThing" resultMap="findthing">
select * from thing
<if test="id!=null">
where id=#{id}
</if>
</select>
<resultMap id="findthing" type="entity.thing">
<result column="me" property="wo"></result>
<result column="Dtime" property="dotime"></result>
</resultMap>
<sql id="thing_fields">
me,others,gob,Rtime,Dtime,place,content
</sql>
<insert id="addThing" useGeneratedKeys="true" keyProperty="id">
insert into thing(<include refid="thing_fields"></include>)
value(#{wo},#{others},#{gob},#{rtime},#{dotime},#{place},#{content})
</insert>
<update id="updatething">
update thing set me=#{wo},
others=#{others},
gob=#{gob},
Rtime=#{Rtime},
Dtime=#{Dtime},
place=#{place},
content=#{content},
ach=#{ach}
where id=#{id}
</update>
</mapper>
addThing.jsp
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: Lenovo
Date: 2019/8/14
Time: 15:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>马嘉骏的小本本</title>
<link rel="stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
<script src="lib/2.2.4/jquery-1.12.4.min.js"></script>
<script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="page-header">
<h1><span class="glyphicon glyphicon-heart"></span>
马嘉骏的小本本 <small> 记录每件事</small></h1>
</div>
</div>
<div class="row">
<div class="jumbotron">
<h1>记录点滴</h1>
<p>当他回首往事的时候,他不会因为虚度年华而悔恨,也不会因为碌碌无为而羞耻</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">获取更多</a></p>
</div>
</div>
<div class="row">
<div class="col-md-8 col col-md-offset-2">
<form class="form-horizontal" action="${pageContext.request.contextPath}/addThing">
<div class="form-group">
<label for="me" class="col-sm-2 control-label">记录人物</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="me" name="me" placeholder="请输入记录人物">
</div>
</div>
<div class="form-group">
<label for="others" class="col-sm-2 control-label">相关对象</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="others" name="others" placeholder="请输入相关对象">
</div>
</div>
<div class="form-group">
<label for="gob" class="col-sm-2 control-label">事情好坏</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="gob" name="gob" placeholder="请输入事情好坏">
</div>
</div>
<div class="form-group">
<label for="dotime" class="col-sm-2 control-label">代办时间</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="dotime" name="dotime" placeholder="请输入代办时间">
</div>
</div>
<div class="form-group">
<label for="place" class="col-sm-2 control-label">发生地点</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="place" name="place" placeholder="请输入事情发生地点">
</div>
</div>
<div class="form-group">
<label for="content" class="col-sm-2 control-label">详细内容</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="content" name="content" placeholder="请输入事情详细内容">
</div>
</div>
<div class="form-group">
<input type="submit" value="提交数据更新" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
thingDao
package Dao;
import utils.SqlSessionFactoryUtils;
import entity.thing;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class thingDao {
private SqlSession sqlSession;
private List<thing> list;
private thing thi;
private SqlSession getSession(){
sqlSession= SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
return sqlSession;
}
public List<thing> findAll(){
try {
list=getSession().selectList("findThing");
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return list;
}
public thing findById(Integer id){
try {
thi=getSession().selectOne("findThing",new thing(id));
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return thi;
}
// 增加一个新用户数据到数据库的方法
public thing addThing(thing thi){
try {
//返回值:是insert执行过程中影响的行数
getSession().insert("addThing",thi);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return thi;
}
// 用于修改事件的方法
public thing updateThing(thing thi){
try {
getSession().update("updatething",thi);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return thi;
}
}
thingAddServlet
package servlet;
import Dao.thingDao;
import entity.thing;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
@WebServlet("/addThing")
public class thingAddServlet extends HttpServlet {
private thingDao thingdao=new thingDao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取要添加的用户数据
String me=req.getParameter("me");
String others=req.getParameter("others");
String gob=req.getParameter("gob");
String dotime=req.getParameter("dotime");
String place=req.getParameter("place");
String content=req.getParameter("content");
//根据用户数据创建一个用户对象
thing thi=new thing(me,others,gob,new Date(),dotime,place,content);
//将对象用户添加到数据库中
thi=thingdao.addThing(thi);
//查看刚新增的用户数据
resp.sendRedirect("detail?id=" + thi.getId());
}
}
28.修改语句
映射配置文件 usersMapper
<update id="updatething">
update thing set me=#{wo},
others=#{others},
gob=#{gob},
Rtime=#{Rtime},
Dtime=#{Dtime},
place=#{place},
content=#{content},
ach=#{ach}
where id=#{id}
</update>
dao/thingDao
package Dao;
import utils.SqlSessionFactoryUtils;
import entity.thing;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class thingDao {
private SqlSession sqlSession;
private List<thing> list;
private thing thi;
private SqlSession getSession(){
sqlSession= SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
return sqlSession;
}
// 用于修改事件的方法
public thing updateThing(thing thi){
try {
getSession().update("updatething",thi);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return thi;
}
}
servlet/thingUpdataServlet
package servlet;
import Dao.thingDao;
import entity.thing;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/updatething")
public class thingUpdataServlet extends HttpServlet {
private thingDao thingdao=new thingDao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取用户要更新的数据
String id=req.getParameter("id");
String me=req.getParameter("me");
String others=req.getParameter("others");
String gob=req.getParameter("gob");
String dotime=req.getParameter("dotime");
String place=req.getParameter("place");
String content=req.getParameter("content");
//创建事件对象
thing thi=new thing(Integer.parseInt(id),me,others,gob,dotime,place,content);
//提交更新
thingdao.updateThing(thi);
//查看更新后的数据
resp.sendRedirect("detail?id="+thi.getId());
}
}
29.删除语句
usersMapper.xml
mapper标签中添加
<delete id="delthing">
delete from thing where id=#{id}
</delete>
Dao/thingDao.java
public void deletething(Integer id){
try {
getSession().delete("delthing",id);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
servlet/thingDeleteServlet
本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!