controller层:
StudentController
package com.kfm.mybatis.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kfm.mybatis.constant.Constant;
import com.kfm.mybatis.model.Student;
import com.kfm.mybatis.services.StudentServices;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Controller
public class StudentController {
private StudentServices studentServices;
@GetMapping("/selectById")
public Student selectById(){
Student student = studentServices.selectById(6);
return student;
}
@RequestMapping("/showAll")
public ModelAndView showAll(Integer pageNumber){
if (pageNumber == null) {
pageNumber = 1; // 默认为1或其他您认为合适的页码
}
PageHelper.startPage(pageNumber,5);
studentServices = new StudentServices();
List<Student> students = studentServices.selectAll();
PageInfo<Student> page = new PageInfo<>(students);
ModelAndView mv = new ModelAndView();
mv.addObject("page",page);
mv.setViewName("studentList");
mv.addObject("list",students);
return mv;
}
@GetMapping ("/deleteById")
public String deleteById(HttpServletResponse response, HttpServletRequest request, RedirectAttributes attributes){
String id = request.getParameter("id");
int i = studentServices.deleteById(Integer.parseInt(id));
if (i > 0){
attributes.addFlashAttribute("message","删除学生信息成功");
request.getSession().setAttribute(Constant.OPERATE_MESSAGE,"删除学生信息成功");
} else {
request.getSession().setAttribute(Constant.OPERATE_MESSAGE,"删除学生信息失败");
attributes.addFlashAttribute("message","删除学生信息失败");
}
return "redirect:/showAll";
}
@PostMapping("/addStudent")
public String addStudent(HttpServletResponse response, HttpServletRequest request,RedirectAttributes attributes){
Student student = new Student();
student.setId(Integer.valueOf(request.getParameter("id")));
student.setName(request.getParameter("name"));
student.setBirth(new Date());
student.setGender(request.getParameter("gender"));
int i = studentServices.addStudent(student);
if (i > 0){
request.getSession().setAttribute(Constant.OPERATE_MESSAGE,"添加学生信息成功");
attributes.addFlashAttribute("message","添加学生信息成功");
}else {
request.getSession().setAttribute(Constant.OPERATE_MESSAGE,"添加学生信息失败");
attributes.addFlashAttribute("message","添加学生信息失败");
}
return "redirect:/showAll";
}
@GetMapping("/addStudent")
public String add(){
return "addStudent";
}
@PostMapping("/updateStudent")
public String updateStudent(HttpServletResponse response, HttpServletRequest request,RedirectAttributes attributes){
Student student = new Student();
String birth = request.getParameter("birth");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date birthDate = null;
if (birth != null && !birth.isEmpty()) {
try {
birthDate = dateFormat.parse(birth);
} catch (ParseException e) {
e.printStackTrace();
}
}
student.setBirth(birthDate);
String id = request.getParameter("id");
if (id != null && !id.isEmpty()) {
student.setId(Integer.valueOf(id));
}
String name = request.getParameter("name");
if (name != null && !name.isEmpty()) {
student.setName(name);
}
String gender = request.getParameter("gender");
if (gender != null && !gender.isEmpty()) {
student.setGender(gender);
}
int i = studentServices.update(student);
if (i > 0){
request.getSession().setAttribute(Constant.OPERATE_MESSAGE,"修改学生信息成功");
attributes.addFlashAttribute("message","修改学生信息成功");
}else {
request.getSession().setAttribute(Constant.OPERATE_MESSAGE,"修改学生信息失败");
attributes.addFlashAttribute("message","修改学生信息失败");
}
return "redirect:/showAll";
}
}
service层:
StudentServices
package com.kfm.mybatis.services;
import com.kfm.mybatis.dao.StudentInfoDao;
import com.kfm.mybatis.model.Student;
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.util.List;
public class StudentServices {
private StudentInfoDao mapper;
private SqlSession sqlSession;
private InputStream in;
public StudentServices(){
try {
in = Resources.getResourceAsStream("mybatis-config01.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = sqlSessionFactoryBuilder.build(in);
sqlSession = build.openSession();
sqlSession = build.openSession(true);
mapper = sqlSession.getMapper(StudentInfoDao.class);
} catch (IOException e) {
e.printStackTrace();
}
}
public Student selectById(int id){
Student student = mapper.selectById(id);
return student;
}
public List<Student> selectAll(){
return mapper.selectAll();
}
public int deleteById(int id){
return mapper.deleteById(id);
}
public int addStudent(Student student){
return mapper.addStudent(student);
}
public int updateStudent(String value,int id){
return mapper.updateStudent(value,id);
}
public int insertStudent(Student student){
return mapper.insertStudent(student);
}
//if标签
public List<Student> selectStudentById(Student student){
return mapper.selectStudentById(student);
}
/**
* where标签
*/
public List<Student> selectStudent1(Student student){
return mapper.selectStudent1(student);
}
/**
* foreach标签
*/
public int deleteStudent(int...ids) {
return mapper.deleteStudent(ids);
}
/**
* trim标签
* @param student
* @return
*/
public List<Student> selectStudent2(Student student){
return mapper.selectStudent2(student);
}
/**
* set标签
* @param student
* @return
*/
public int update(Student student){
return mapper.update(student);
}
/**
* choose标签
* @param student
* @return
*/
public List<Student> selectChoose(Student student){
return mapper.selectChose(student);
}
public void close() {
sqlSession.commit();
try {
sqlSession.close(); // 先关闭SqlSession,确保事务处理完毕
in.close(); // 再关闭InputStream
} catch (IOException e) {
e.printStackTrace();
}
}
}
model层:
Student
package com.kfm.mybatis.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.ibatis.type.Alias;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Alias("student")
public class Student implements Serializable {
private Integer id;
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birth;
private String gender;
private static final long serialVersionUID = 1L;
}
resource层中的templates
studentList.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" th:href="@{css/bootstrap.css}">
<script th:src="@{js/jquery.min.js}"></script>
<script th:src="@{js/bootstrap.min.js}"></script>
<style>
table{
width: 100%;
border-collapse: collapse;
margin: 0 auto;
}
table caption{
font-size: 2em;
font-weight: bold;
margin: 1em 0;
}
th,td{
border: 1px solid #999;
text-align: center;
padding: 20px 0;
}
table thead tr{
background-color: #008c8c;
color: #fff;
}
table tbody tr:nth-child(odd){
background-color: #eee;
}
table tbody tr:hover{
background-color: #ccc;
}
table tbody tr td:first-child{
color: #f40;
}
table tfoot tr td{
text-align: right;
padding-right: 20px;
}
/*增加学生按钮的样式*/
#createButton {
background-color: #f2f2f2; /* 设置背景颜色 */
color: #333333; /* 设置文本颜色 */
border: none; /* 移除边框 */
padding: 10px 20px; /* 设置内边距 */
font-size: 16px; /* 设置字体大小 */
border-radius: 5px; /* 设置圆角 */
cursor: pointer; /* 设置鼠标指针为手形 */
}
#createButton:hover {
background-color: #e6e6e6; /* 鼠标悬停时的背景颜色 */
}
/* 修改 "共" 和 "条数据" 的样式 */
.pagination .total-text {
margin: 0 5px; /* 添加一些水平间距 */
font-weight: bold; /* 加粗文本 */
}
/* 设置总页数的样式 */
.pagination .total-pages {
margin: 0 5px; /* 添加一些水平间距 */
font-weight: bold; /* 加粗文本 */
}
.info-img {
width: 40px;
}
</style>
</head>
<body>
<!--*******************************************************添加学生信息************************************************-->
<form action="/addStudent" method="get">
<button id="createButton" >添加</button>
</form>
<!-- *************************************************展示学生信息表***********************************************-->
<table>
<caption>学生信息表</caption>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>birth</th>
<th>gender</th>
<th>method</th>
</tr>
</thead>
<tbody>
<tr th:each="student : ${list}">
<td th:text="${student.id}"></td>
<td th:text="${student.name}"></td>
<td th:text="${student.birth}"></td>
<td th:text="${student.gender}"></td>
<td>
<a th:href="@{'/deleteById?id=' + ${student.id}}" class="btn btn-info">删除</a>
<!-- <button type="button" class="btn btn-primary" data-loggle="modal" data-traget="#exampleModal" th:data-whatever="${student.id}">修改</button> 有问题-->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"
th:data-whatever="${student.id}">修改
</button>
</td>
</tr>
</tbody>
</table>
<!-- ***************************************修改学生信息***************************************************************-->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">修改信息</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="/updateStudent" method="post">
<div class="form-group">
<!-- <label for="id" class="col-form-label">学生编号:</label>-->
<input type="text" class="form-control" id="id" name="id" hidden>
</div>
<div class="form-group">
<label for="name" class="col-form-label">学生姓名:</label>
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="form-group">
<label for="gender" class="col-form-label">学生性别:</label>
<input type="text" class="form-control" id="gender" name="gender">
</div>
<div class="form-group">
<label for="birth" class="col-form-label">出生日期:</label>
<input type="date" class="form-control" id="birth" name="birth">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
<button type="submit" class="btn btn-primary">提交</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!--*************************************************分页************************************************************-->
<nav aria-label="...">
<ul class="pagination justify-content-center">
<!-- <li class="page-item">-->
<!-- 共-->
<!-- <span th:text="${page.getTotal()}"></span>-->
<!-- 条-->
<!-- </li>-->
<!-- 上一页按钮 -->
<li th:class="${page.isHasPreviousPage() ? 'page-item' : 'page-item disabled'}">
<a class="page-link"
th:href="@{/showAll(pageNumber=${page.getPrePage()})}">上一页</a>
</li>
<!-- <li class="page-item">共<span th:text="${page.getPages()}"></span>页数</li>-->
<!-- 页码列表 -->
<li th:each="num : ${page.getNavigatepageNums()}" th:class="${num==page.getPageNum()} ? 'page-item active' : 'page-item'">
<a class="page-link"
th:href="@{/showAll(pageNumber=${num})}"
th:text="${num}"></a>
</li>
<!-- 下一页按钮 -->
<li th:class="${page.isHasNextPage()} ? 'page-item' : 'page-item disabled'">
<a class="page-link"
th:href="@{/showAll(pageNumber=${page.getNextPage()})}">下一页</a>
</li>
<!-- 显示总页数 -->
<!-- <li class="page-item">-->
<!-- 共-->
<!-- <span th:text="${page.getPages()}" class="total-pages"></span>-->
<!-- 页-->
<!-- </li>-->
</ul>
</nav>
<!--这段代码是用于在Bootstrap模态框(Modal)显示之前,,将按钮的data-whatever属性值设置到模态框中对应输入框的值。-->
<script>
$('#exampleModal').on('show.bs.modal', function (event) {
let button = $(event.relatedTarget)
let id = button.data('whatever')
let modal = $(this)
modal.find('#id').val(id)
})
</script>
<!--*********************************************轻量弹框**************************************************************-->
<div aria-live="polite" aria-atomic="true" style="position: relative; min-height: 200px;">
<div class="toast" style="position: absolute; top: 0; right: 0; " id="message-info" data-delay="3000">
<div class="toast-header">
<img th:src="@{images/001.jpg}" class="rounded mr-2 info-img" alt="...">
<strong class="mr-auto">学生信息</strong>
<small>11 mins ago</small>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="toast-body">
[(${message})]
</div>
</div>
</div>
<script th:inline="javascript">
$(document).ready(function() {
let msg = [[${message}]];
if (msg) {
// 显示弹窗
$('#message-info').toast('show');
// 设置延迟关闭弹窗,例如 5 秒后关闭
setTimeout(function() {
$('#message-info').toast('hide');
}, 9000); // 9000 毫秒 = 9 秒
}
});
</script>
</body>
</html>
addStudent.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表单样式示例</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
text-align: center;
}
form {
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
width: 300px;
margin: 0 auto;
}
form input {
width: 100%;
padding: 10px;
margin: 5px 0;
border: 1px solid #ccc;
border-radius: 3px;
}
button[type="submit"] {
width: 100%;
padding: 10px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 3px;
cursor: pointer;
}
button[type="submit"]:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<form action="addStudent" method="post">
<label for="id">ID:</label>
<input type="text" id="id" name="id">
<label for="name">姓名:</label>
<input type="text" id="name" name="name">
<br>
<label for="birth">生日:</label>
<input type="text" id="birth" name="birth">
<br>
<label for="gender">性别:</label>
<input type="text" id="gender" name="gender">
<br>
<button type="submit">提交</button>
</form>
</body>
</html>
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>
<typeAliases>
<package name="com.kfm.mybatis.model"/>
</typeAliases>
<!-- 配置分页插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 指定方言 -->
<property name="helperDialect" value="mysql"/>
</plugin>
</plugins>
<!--配置mybatis的环境-->
<environments default="mysql">
<!--配置MySQL的环境-->
<environment id="mysql">
<!--配置事务的类型-->
<transactionManager type="JDBC" />
<!--配置连接数据库的信息:用的是数据源(连接池)-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/test5"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--告知mybatis映射配置的位置-->
<mappers>
<mapper resource="IUserInfoDao.xml"/>
<mapper resource="StudentInfoDao.xml"/>
</mappers>
</configuration>
studentInfoDao.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="com.kfm.mybatis.dao.StudentInfoDao">
<!-- 简化sql语句,与<include连用>-->
<sql id="mySql">id,name,birth,gender</sql>
<insert id="addStudent" parameterType="student">
insert into student (id,name,birth,gender) values (#{id},#{name},#{birth},#{gender})
</insert>
<insert id="insertStudent"></insert>
<update id="updateStudent" >
update student set name = #{param1} where id = #{param2}
</update>
<!-- set标签:更新,包含语句前+set并删除最后一个,-->
<update id="update">
update student
<set>
<if test="name != null">
name = #{name},
</if>
<if test="birth != null">
birth = #{birth},
</if>
<if test="gender">
gender = #{gender},
</if>
</set>
where id = #{id}
</update>
<delete id="deleteById">
delete from student where id = #{id}
</delete>
<select id="selectById"
resultType="student">
select
<include refid="mySql"/>
from student where id = #{id}
</select>
<select id="selectAll"
resultType="student">
select * from student
</select>
<!-- if标签 为保证sql语句的完整性,添加where 1 = 1 -->
<select id="selectStudentById" resultType="com.kfm.mybatis.model.Student">
select * from student where 1 = 1
<if test="id != null">
and id = #{id}
</if>
<if test="name != null">
and name = #{name}
</if>
<if test="birth != null">
and birth = #{birth}
</if>
<if test="gender != null">
and gender = #{gender}
</if>
</select>
<!-- where标签:只会在子元素返回任何内容的时候加入子句,并拼接where,把第一个满足条件的and删除-->
<select id="selectStudent1" resultType="com.kfm.mybatis.model.Student">
select * from student
<where>
<if test="id != null">
and id = #{id}
</if>
<if test="name != null">
and name = #{name}
</if>
<if test="birth != null">
and birth = #{birth}
</if>
<if test="gender != null">
and gender = #{gender}
</if>
</where>
</select>
<!-- trim标签:可去除sql中多余的and,或给sql前拼接内容 prefix给子标签中的语句前面拼接,prefixOverrides删除子标签中指定的字符-->
<select id="selectStudent2" resultType="com.kfm.mybatis.model.Student">
select * from student
<where>
<trim prefixOverrides="AND">
<if test="id != null">
and id = #{id}
</if>
<if test="name != null">
and name = #{name}
</if>
<if test="birth != null">
and birth = #{birth}
</if>
<if test="gender != null">
and gender = #{gender}
</if>
</trim>
</where>
</select>
<!-- choose标签:多个条件选择, when中的test中添加条件 when=>if when=>else if otherwise=>else-->
<select id="selectChose" resultType="com.kfm.mybatis.model.Student">
select * from student
<where>
<choose>
<when test="id != null">
and id = #{id}
</when>
<when test="name != null">
and name = #{name}
</when>
<when test="birth != null">
and name = #{birth}
</when>
<when test="gender != null">
and gender = #{gender}
</when>
<otherwise>
</otherwise>
</choose>
</where>
</select>
<!-- foreach标签:collection:array => 数组 ,list => list , Mao/对象 => key item:给对象起名 open:以什么开始 close:以什么结束 separator:以什么分割-->
<delete id="deleteStudent">
delete from student
<where>
<foreach collection="array" item="id" open="id in (" close=")" separator=",">
#{id}
</foreach>
</where>
</delete>
</mapper>