MyBatis+Spring Boot+MySQL简单的增删改查

前言

     开发工具:IntelliJ IDEA 、MySQL。
     HTML页面使用的是:thymeleaf模板。
     表单提交方式使用的是Ajax。
     用到的前端框架是bootstrap

数据库及表的创建

-- 创建数据库
CREATE DATABASE IF NOT EXISTS shoop DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
-- 创建一个测试表
create table test_one(
  testId int auto_increment primary key,
  testName varchar(200),
  testAge int,
  testDate date
)
-- 添加数据
insert into test_one(testName,testAge,testDate) values('张三',18,'1998-01-01'),('李四',19,'1997-11-01')

打开IDEA 创建项目并配置好pom.xml文件和application.properties数据源连接

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springboot.demo</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- spring boot mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>
        <!-- 添加thymeleaf支持:类似于jsp的视图模板 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.properties

#数据源
spring.datasource.url=jdbc:mysql://localhost:3306/shoop?serverTimezone=Asia/Shanghai&useSSL=false&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

实体类(entity)

public class Test_one {
    private Integer testId;
    private String testName;
    private Integer testAge;
    //日期时间的格式转换
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date testDate;
    }
    //省略getter和setter方法    

接口(mapper)

@Mapper
public interface Test_oneMapper {
    //查询全部信息
    public List<Test_one> test_oneAll();
    //添加信息
    public int insert(Test_one test_one);
     //根据id查询详细信息
    public Test_one selectId(Integer testId);
    //修改信息
    public int update(Test_one test_one);
    //删除信息
    public int deletes(Integer testId);
}

myBatis配置文件(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.springboot.mapper.Test_oneMapper">
    <!-- 查询所有信息 -->
    <select id="test_oneAll" resultType="com.springboot.entity.Test_one">
        select testName,testAge,testDate from test_one
    </select>
    <!-- 添加信息 -->
    <insert id="insert" parameterType="com.springboot.entity.Test_one">
        insert into test_one(testName,testAge,testDate) values(#{testName},#{testAge},#{testDate})
    </insert>
    <!-- 根据id查询信息 -->
    <select id="selectId" resultType="com.springboot.entity.Test_one">
        select testId,testName,testAge,testDate from test_one where testId=#{testId}
    </select>
    <!-- 修改信息 -->
    <update id="update" parameterType="com.springboot.entity.Test_one">
        update test_one set testName=#{testName},testAge=#{testAge},testDate=#{testDate} where testId=#{testId}
    </update>
    <!-- 删除信息 -->
    <delete id="deletes" parameterType="com.springboot.entity.Test_one">
        delete from test_one where testId=#{testId}
    </delete>
</mapper>

业务层(service)

public interface ITest_oneService {
    //查询全部信息
    public List<Test_one> test_oneAll();
    //添加信息
    public int insert(Test_one test_one);
    //根据id查询详细信息
    public Test_one selectId(Integer testId);
    //修改信息
    public int update(Test_one test_one);
    //删除信息
    public int deletes(Integer testId);
}

业务实现层(service.impl)

@Service
public class Test_oneServiceImpl implements ITest_oneService {
    //定义mapper数据库访问对象
    @Resource
    Test_oneMapper mapper;
    //查询全部信息
    @Override
    public List<Test_one> test_oneAll() {
        return mapper.test_oneAll();
    }
    //添加信息
    @Override
    public int insert(Test_one test_one) {
        return mapper.insert(test_one);
    }
     //根据id查询详细信息
    @Override
    public Test_one selectId(Integer testId) {
        return mapper.selectId(testId);
    }
    //修改信息
    @Override
    public int update(Test_one test_one) {
        return mapper.update(test_one);
    }
    //删除信息
    @Override
    public int deletes(Integer testId) {
        return mapper.deletes(testId);
    }
}

逻辑控制层(Controller)

@Controller
//定义父类访问路径
@RequestMapping("/Test")
public class Test_oneController {
    @Resource
    ITest_oneService service;

    //设置访问路径
    @RequestMapping("/test_oneAllList")
    //查询全部信息
    public String test_oneAll(Model model){
        List<Test_one> test_oneAllList = service.test_oneAll();
        model.addAttribute("test_oneAllList",test_oneAllList);
        return "/front/home";
    }
     //设置添加页面的访问路径
    @RequestMapping("/select")
    public String test_oneAll(){
        return "/front/insert";
    }
    //设置访问路径
    @RequestMapping("/test_oneInsert")
    @ResponseBody
    //添加信息
    public Map<String,String> insert(Test_one test_one){
        Map<String,String> map = new HashMap<String, String>();
        int insert = service.insert(test_one);
        if(insert > 0){
            map.put("result","提交成功");
        }else{
            map.put("result","提交失败");
        }
        return map;
    }
     //根据id查询详细信息
    @RequestMapping("/selectId")
    @ResponseBody
    public Object selectId(Integer testId){
        Test_one sel = service.selectId(testId);
        return sel;
    }
    //修改信息
    @RequestMapping("/update")
    @ResponseBody
    public Map<String,String> update(Test_one test_one){
        Map<String,String> map = new HashMap<String, String>();
        int num = service.update(test_one);
        if(num > 0){
            map.put("result","修改成功");
        }else{
            map.put("result","修改失败");
        }
        return map;
    }
    //删除信息,在实际开发过程中,所谓的删除有时并不是真正意义上的删除,只是修改了状态,让用户查询不出来了,
    //其实后端还是可以查询到的,开发过程中这种删除的方法也时很少用到的
    @RequestMapping("/deletes")
    @ResponseBody
    public int deletes(Integer testId){
        int num = service.deletes(testId);
        if(num > 0){
            return 1;
        }else {
            return 0;
        }
    }
}

首页HTML

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.com">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <script src="/js/jquery.min.js"></script>
    <script src="/js/bootstrap.min.js"></script>
</head>
<style>
    #tab{
        position: relative;
        left: 600px;
    }
</style>
<body>
<table id="tab">
    <tr>
        <td>编号</td>
        <td>姓名</td>
        <td>年龄</td>
        <td>出生日期</td>
        <td>操作</td>
    </tr>
    <th:block th:each="test:${test_oneAllList}">
    <tr>
        <td class="testId" th:text="${test.testId}"></td>
        <td><span th:text="${test.testName}"></span></td>
        <td><span th:text="${test.testAge}"></span></td>
        <td><span th:text="${#dates.format(test.testDate,'yyyy-MM-dd')}"></span></td>
        <td>
            <button onclick="select(this)" class="btn btn-default" data-toggle="modal" data-target="#myModal">修改</button>
            <button onclick="deletes(this)">删除</button>
        </td>
    </tr>
    </th:block>
</table>
<!-- 模态框(Modal) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    修改
                </h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="testId"/>
                <div>
                    请输入修改名称:<input id="testName" type="type"/>
                </div>
                <div>
                    请输入修改年龄:<input id="testAge" type="type"/>
                </div>
                <div>
                    请输入修改日期:<input id="testDate" type="date"/>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                </button>
                <button type="button" id="sub" class="btn btn-primary">
                    提交更改
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>

</body>
<script>
    //查询
    function select(res) {
        var testId = $(res).parent().siblings(".testId").html();
        $.ajax({
            url:"/Test/selectId",
            data:{
                testId:testId
            },
            success: function(data){
                $("#testId").val(data.testId);
                $("#testName").val(data.testName);
                $("#testAge").val(data.testAge);
                var time = new Date(data.testDate).toJSON();
                var d = new Date(time);
                //格式化日,如果小于9,前面补0
                var day = ("0" + d.getDate()).slice(-2);
                 //格式化月,如果小于9,前面补0
                var month = ("0" + (d.getMonth()+1)).slice(-2);
                var times=d.getFullYear() + '-' + (month) + '-' + (day);
                $("#testDate").val(times);
            },
            error:function (data) {
                alert("没有该商品信息");
            },
        });
    }
    //修改
    $("#sub").click(function() {
        var testId = $("#testId").val();
        var testName = $("#testName").val();
        var testAge = $("#testAge").val();
        var testDate = $("#testDate").val();
        $.ajax({
            url:"/Test/update",
            data:{
                testId:testId,
                testName:testName,
                testAge:testAge,
                testDate:testDate
            },
            success:function(data) {
               if(data.result == "修改成功"){
                   alert("修改成功");
                   //跳转到首页
                   window.location.href = 'http://localhost:8080/Test/test_oneAll';
               }else{
                   alert("修改失败");
                }
            },
            error:function() {
                alert("修改时出现错误")
            }
        })
    })
    //删除
    function deletes(res){
        //确认对话框
        if(window.confirm('确定要删除该条记录吗?')){
            var testId = $(res).parent().siblings(".testId").html();
            $.ajax({
                url:"/Test/deletes",
                data:{
                    testId:testId
                },
                success:function(data) {
                    if(data == 1){
                        alert("删除成功");
                        //跳转到首页
                        window.location.href = 'http://localhost:8080/Test/test_oneAll';
                    }else{
                        alert("删除失败");
                    }
                },
                error:function() {
                    alert("删除时出现错误")
                }
            })
            return true;
        }else{
            return false;
        }
    }
</script>
</html>

添加HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/js/jquery-1.7.1.min.js"></script>
</head>
<body>
<form id="formId">
<div>
    姓名:<input type="text" name="testName" id="testName"/><br/>
    年龄:<input type="text" name="testAge" id="testAge"/><br/>
    出生日期:<input type="date" name="testDate" id="testDate"/><br/>
    <input type="button" id="add" value="添加">
</div>
</form>
</body>
<script>
  $("#add").click(function(){
      var name = $("#testName").val();
      var age = $("#testAge").val();
      var date = $("#testDate").val();
      $.ajax({
          type:"POST",
          url:"/Test/test_oneInsert",
          //序列化表单(数据量大时建议使用)
          //data:$("#formId").serialize(),
          data:{
              testName:name,
              testAge:age,
              testDate:date
          },
          dataType:"json",
          success:function (data) {
              if(data.result == "提交成功") {
                  alert("添加成功");
                  //跳转到首页
                  window.location.href = 'http://localhost:8080/Test/test_oneAll';
              }else{
                  alert("添加失败");
              }
          },
          error:function (data) {
              alert("添加时发生错误");
          }
      })
  });
</script>
</html>

上述的代码只是一个表和一次操作一列数据的代码,当然myBatis的优势在于可以批量操作,这样可以让我们省去很多的代码量。
项目源码https://pan.baidu.com/s/1C_u_YlqnvtaFaLda_1J9xA提取码:qhat
如果这篇文章对各位有用,请点个赞,给个支持,谢谢!!!

发布了22 篇原创文章 · 获赞 2 · 访问量 1144

猜你喜欢

转载自blog.csdn.net/javaasd/article/details/105034006