SpringBoot + MyBatis 实现对员工的增删改查
更新:HHH   时间:2023-1-7


SpringBoot + MyBatis 实现对员工的增删改查

一、使用idea新建SpringBoot项目

File——>New——>Project——>Spring Assistant——>Next——>修改报名,项目名等信息——>Next——>
在web中选中web,在SQL中选中MySQL、JDBS、MyBatis——>Next——>Finish

二、修改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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.qiuuuu</groupId>
    <artifactId>empboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>empboot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.2.0</version>
        </dependency>
        <!-- Spring Boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

        <!--启动时启动内置tomcat -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>

        <!--对Jsp支持 -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

        <!-- 支持jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- MySql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>

        <!-- servlet 依赖包 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- JSTL (JSP standard Tag Library) JSP 标准标签库 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <!-- <scope>provided</scope>-->
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.27</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.23</version>
        </dependency>

    </dependencies>
</project>

三、新建包和相应的接口和类


1、新建包

2、写controller
(1)、EmpController

package cn.qiu.controller;

import cn.qiu.entity.Emp;
import cn.qiu.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class EmpController {
    @Resource
    EmpService empService;

    @RequestMapping("/a")
    public String a(){
        return "emp";
    }

    @ResponseBody
    @RequestMapping("/aa")
    public List<Emp> aa(){
        return empService.findAll();
    }
}

(2)、AddEmpController

package cn.qiu.controller;

import cn.qiu.service.AddEnpService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AddEmpController {
    @Autowired
    AddEnpService addEnpService;
    @ResponseBody
    @RequestMapping("addEmp")
    public void addEmp(@Param("name") String name,@Param("sex") String sex,@Param("age") int age,
                       @Param("address") String address){
        addEnpService.addEmp(name,sex,age,address);

    }
}

(3)、DeleteEmpController

package cn.qiu.controller;

import cn.qiu.service.DeleteEmpService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class DeleteEmpController {

    @Autowired
    DeleteEmpService deleteEmpService;

    @ResponseBody
    @RequestMapping("/delete")
    public void deleteByName(@Param("name") String name){
        System.out.println("controller"+name);
        deleteEmpService.deleteByName(name);
    }
}

3、写service
(1)、EmpService

package cn.qiu.service;

import cn.qiu.entity.Emp;

import java.util.List;

public interface EmpService {
    public List<Emp> findAll();
}

(2)、AddEmpDao

package cn.qiu.dao;

import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface AddEmpDao {
    public void addEmp(String name,String sex,int age,String address);
}

(3)、DeleteEmpDao

package cn.qiu.dao;

import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface DeleteEmpDao {
    void deleteByName(String name);
}

4、写serviceImpl
(1)、EmpServiceImpl

package cn.qiu.service.impl;

import cn.qiu.dao.EmpDao;
import cn.qiu.entity.Emp;
import cn.qiu.service.EmpService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service(value = "userService")
public class EmpServiceImpl implements EmpService {
    @Resource
    EmpDao empDao;

    @Override
    public List<Emp> findAll() {
        return empDao.findAll();
    }
}

(2)、AddEmpServiceImpl

package cn.qiu.service.impl;

import cn.qiu.dao.AddEmpDao;
import cn.qiu.service.AddEnpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AddEmpServiceImpl implements AddEnpService {
    @Autowired
    AddEmpDao addEmpDao;
    @Override
    public void addEmp(String name, String sex, int age, String address) {
        addEmpDao.addEmp(name,sex,age,address);
    }
}

(3)、DeleteEmpServiceImpl

package cn.qiu.service.impl;

import cn.qiu.dao.DeleteEmpDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DeleteEmpServiceImpl implements cn.qiu.service.DeleteEmpService {
    @Autowired
    DeleteEmpDao deleteDao;
    @Override
    public void deleteByName(String name) {
        System.out.println("serviceImpl"+name);
        deleteDao.deleteByName(name);
    }
}

5、写Dao
(1)、EmpDao

package cn.qiu.dao;

import cn.qiu.entity.Emp;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface EmpDao {
    public List<Emp> findAll();
}

(2)、AddEmpDao

package cn.qiu.dao;

import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface AddEmpDao {
    public void addEmp(String name,String sex,int age,String address);
}

(3)、DeleteEmpDao

package cn.qiu.dao;

import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface DeleteEmpDao {
    void deleteByName(String name);
}

6、写Mapper
(1)、AddEmpMapper

<?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="cn.qiu.dao.EmpDao" >
    <select id="findAll" resultType="cn.qiu.entity.Emp">
        select name,sec sex,agg age,addre address from Person;
    </select>

</mapper>

(2)、AddEmpMapper

<?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="cn.qiu.dao.AddEmpDao" >
    <insert id="addEmp" >
        insert into person values(#{0},#{1},#{2},#{3})
    </insert>
</mapper>

(3)、DeleteEmpMapper

<?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="cn.qiu.dao.DeleteEmpDao" >
    <delete id="deleteByName"  >
        delete from person where name=#{name}
    </delete>
</mapper>

四、新建数据库和表

CREATE TABLE `person` (
  `name` varchar(10) DEFAULT NULL,
  `sec` varchar(10) DEFAULT NULL,
  `agg` int(10) DEFAULT NULL,
  `addre` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `person` VALUES ('qiuuuu', 'm', '18', 'china');
INSERT INTO `person` VALUES ('chi', 'f', '18', 'china');
INSERT INTO `person` VALUES ('james', 'm', '30', 'usa');
INSERT INTO `person` VALUES ('kebi', 'm', '38', 'usa');
INSERT INTO `person` VALUES ('zhangsan', 'm', '10', 'china');
INSERT INTO `person` VALUES ('zhang', 'f', '35', 'china');

五、新建springboot配置文件application.yml

#设置Tomcat端口,默认8080
server.port=8081
#设置项目ContextPath
#server.context-path=/
#设置Tomcat编码
server.tomcat.uri-encoding=UTF-8
#设置视图解析器路径
spring.mvc.view.prefix=/WEB-INF/JSP/
#设置视图解析器后缀
spring.mvc.view.suffix=.jsp

#数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=qiuhongchijuan12
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#配置.xml文件路径(mapper文件位置)
mybatis.mapper-locations=classpath:mapper/*.xml
#配置模型路径(实体类的位置)
mybatis.type-aliases-package=cn.qiu.entity

六、写静态页面

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <script src="js/jquery-1.11.1.js"></script>
            <script type="text/javascript">
                $(function(){//页面加载完成就会执行此代码
                    setInterval(quoto,50000000000);//每隔5秒钟执行quoto函数
                });
                function quoto(){//该函数通过调用ajax对象(AMLHttpRequest)向服务器发送异步请求,服务器返回一个描述股票信息的字符串,通过解析json字符串,获得股票信息,然后更新表格
                    $.ajax({//利用jQuery提供的方法向服务器发送异步请求
                        "url":"aa",
                        "type":"post",
                        "dataType":"json",
                        "success":function(stocks){
                            //$.ajax会自动将json字符串转换成JavaScript对象
                            //清空tbody
                            $('#tb1').empty();
                            for(i=0;i<stocks.length;i++){
                                var s=stocks[i];
                                //更新表格
                                $('#tb1').append('<tr><td>'+s.name+'</td><td>'+s.sex+'</td><td>'+s.age+'</td><td>'+s.address+'</td></tr>');

                            }
                        }
                    });
                }

            </script>
        <script type="text/javascript">
            function loadXMLDoc()
            {
            var xmlhttp;
            if (window.XMLHttpRequest)
              {// code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
              }
            else
              {// code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
              }
            xmlhttp.onreadystatechange=function()
              {
              if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
                }
              }
            xmlhttp.open("GET","/ajax/demo_get.asp",true);
            xmlhttp.send();
            }
        </script>
        <style type="text/css">
            table, tr, td
              {
              border:1px solid green;
              }

            td
              {
              background-color:green;
              color:white;
              }
        </style>
    </head>
    <body>
        <div>
            <table>
                <thead>
                    <tr>
                        <td>Name</td>
                        <td>Sex</td>
                        <td>age</td>
                        <td>address</td>
                    </tr>
                </thead>
                <tbody id="tb1">

                </tbody>
            </table>
        </div>
        <div>
            <input id="delete" onclcik="loadXMLDoc" type="button" value="delete">
        </div>
        <div id="myDiv">

        </div>
    </body>
</html>

七、测试

1、查询person表中所有数据
http://127.0.0.1:8081/html/a.html

2、删除表中名字为zhansan的信息
http://127.0.0.1:8081/addEmp?name=zhangsan
3、添加
http://127.0.0.1:8081/addEmp?name=zhang&&sex=f&&age=35&&address=china

返回开发技术教程...