idea使用SpringBoot和Spring和Mybatis来实现增删改查

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_43067223/article/details/84329290

需求:

使用新SSM来实现增删改查

步骤

第一步:看最终包结构

在这里插入图片描述

  • 纠正:数据库连接池部分还有整合mybatis和springboot
  • 这里主要是导入依赖的jar包

第二步:配置pom.xml

  • 导包springBoot支持jdk1.8以上的,所以电脑要安装jdk.1.8
<?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>com.aaa</groupId>
  <artifactId>SpringbootMybatisDemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SpringbootMybatisDemo Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
  <!-- Maven项目之间不仅存在多模块的聚合关系,而且Maven项目之间还可以存在相互继承的关  系。Maven项目之间的继承关系通过<parent>表示,当前项目则是spring-boot-starter-parent的一个子项目大部分配置都可以使用继承-->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
    <relativePath/>
  </parent>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- 核心模块,包括自动配置支持、日志支持 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.2</version>
    </dependency>
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.4.0</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>SpringbootMybatisDemo</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

第三步:application.properties

spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=scott
spring.datasource.password=luruihua
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
#实体别名
mybatis.typeAliasesPackage=com.aaa.sb.entity
#mapper文件扫描
mybatis.mapperLocations=classpath\:mapper/*.xml
#工程名
server.servlet.context-path=/sb
#端口号
server.port=8080
#tomcat编码
server.tomcat.uri-encoding=UTF-8
  • 配置结束

第五步:java代码

DeptController

package com.aaa.sb.controller;

import com.aaa.sb.service.DeptService;
import com.aaa.sb.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * className:DeptController
 * discription:
 * author:zz
 * createTime:2018-11-21 11:32
 */
@RestController
@RequestMapping("/dept")
public class DeptController {

    //依赖注入
    @Autowired
    private DeptService deptService;

    /**
     * 部门列表方法
     * @return
     */
    @RequestMapping("/list")
    public Object list(){
        List<Map> list = deptService.getList();
        return list;
    }

    /**
     * 添加
     * @return
     */
    @RequestMapping("/insertDept")
    public Object add(@RequestParam Map map){
        int i = deptService.insertDept(map);
        Map map1 = new HashMap();
        if (i > 0) {
            map1.put("msg","添加成功!");
        } else {
            map1.put("msg","添加失败!");
        }
        return map1;
    }
    /**
     * 更新
     * @return
     */
    @RequestMapping("/updateDeptMsg")
    public Object updateDeptMsg(@RequestParam Map map){
        int i = deptService.updateDeptMsg(map);
        Map map1 = new HashMap();
        if (i > 0) {
            map1.put("msg","更新成功!");
        } else {
            map1.put("msg","更新失败!");
        }
        return map1;
    }
    /**
     * 删除新闻
     * @return
     */
    @RequestMapping("/deleteOne")
    public Object deleteOne(@RequestParam Map map) {
        int i = deptService.deleteOne(map);
        Map map1 = new HashMap();
        if (i > 0) {
            map1.put("msg","删除成功!");
        } else {
            map1.put("msg","删除失败!");
        }
        return map1;
    }
    /**
     * 通过deptno查dept
     * @return
     */
    @RequestMapping("/selectDeptById")
    public Object selectDeptById(@RequestParam Map paramMap, Model model) {
        List<Map> deptList = deptService.selectDeptById(paramMap);
        return deptList;
    }
}

deptService.java

package com.aaa.sb.service;

import java.util.List;
import java.util.Map;

/**
 * className:DeptService
 * discription:
 * author:zz
 * createTime:2018-11-21 11:28
 */
public interface DeptService {
    /**
     * 部门列表查询
     * @return
     */
    List<Map> getList();
    /**
     * 获取总数量
     * @return
     */
    int getPageCount(Map map);

    /**
     * 部门添加
     * @param map
     * @return
     */
    int insertDept(Map map);

    /**
     * 通过deptno查部门
     * @param paramMap
     * @return
     */
    List<Map> selectDeptById(Map paramMap);

    /**
     * 更新
     * @param map
     * @return
     */
    int updateDeptMsg(Map map);

    /**
     * 删除
     * @param map
     * @return
     */
    int deleteOne(Map map);
}

deptServiceImpl

package com.aaa.sb.service;

import com.aaa.sb.dao.DeptDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * className:DeptServiceImpl
 * discription:
 * author:zz
 * createTime:2018-11-21 11:29
 */
@Service
public class DeptServiceImpl implements  DeptService {

    //依赖注入
    @Autowired
    private DeptDao deptDao;

    /**
     * 部门查询
     * @return
     */
    @Override
    public List<Map> getList() {

        return deptDao.getList();
    }

    @Override
    public int getPageCount(Map map) {
        return deptDao.getPageCount(map);
    }

    /**
     * 部门添加
     * @param map
     * @return
     */
    @Override
    public int insertDept(Map map) {
        return deptDao.insertDept(map);
    }

    /**
     * 通过deptno查dept
     * @param paramMap
     * @return
     */
    @Override
    public List<Map> selectDeptById(Map paramMap) {
        return deptDao.selectDeptById(paramMap);
    }

    /**
     * 更新
     * @param map
     * @return
     */
    @Override
    public int updateDeptMsg(Map map) {
        return deptDao.updateDeptMsg(map);
    }

    /**
     * 删除
     * @param map
     * @return
     */
    @Override
    public int deleteOne(Map map) {
        return deptDao.deleteOne(map);
    }
}

deptDao.java

package com.aaa.sb.dao;

import java.util.List;
import java.util.Map;

/**
 * className:DeptDao
 * discription:
 * author:zz
 * createTime:2018-11-21 11:22
 */
public interface DeptDao {

    /**
     * 部门列表查询
     * @return
     */
    List<Map>  getList();

    /**
     * 获取总数量
     * @return
     */
    int getPageCount(Map map);

    /**
     * 部门添加
     * @param map
     * @return
     */
    int insertDept(Map map);

    /**
     * 通过deptno查dept
     * @param paramMap
     * @return
     */
    List<Map> selectDeptById(Map paramMap);

    /**
     * 更新
     * @param map
     * @return
     */
    int updateDeptMsg(Map map);

    /**
     * 删除
     * @param map
     * @return
     */
    int deleteOne(Map map);
}

SpringBootMainApplication.java

package com.aaa.sb;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * className:SpringBootMainApplication
 * discription:
 * author:luRuiHua
 * createTime:2018-11-21 15:15
 */
@SpringBootApplication
@MapperScan("com.aaa.sb.dao")
public class SpringBootMainApplication {
    /**
     * 主函数
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMainApplication.class);

    }
}

DeptDaoMapper.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.aaa.sb.dao.DeptDao">
    <!--部门列表查询-->
    <select id="getList" resultType="map">
        <!-- select * from (
        select rownum rn,t.deptno,t.dname,t.loc from dept t where rownum &lt;#{end}
         ) a where a.rn &gt; #{start}-->
      select * from dept
    </select>
    <!--部门数量-->
    <select id="getPageCount" resultType="int">
        select count(*) from dept
    </select>
    <!--部门添加-->
    <insert id="insertDept">
        insert into dept values (seq_dept_id.nextval,#{dname},#{loc})
    </insert>
    <!--通过deptno查询dept-->
    <select id="selectDeptById" resultType="map">
        select deptno,dname,loc from dept where deptno = #{deptNo}
    </select>
    <!--更新-->
    <update id="updateDeptMsg">
        update dept
        <set>
            <if test="dname != null">
                dname = #{dname},
            </if>
            <if test="loc != null">
                loc = #{loc},
            </if>
        </set>
        where deptno = #{deptNo}
    </update>
    <!--删除-->
    <delete id="deleteOne">
        delete from dept where deptno = #{deptNo}
    </delete>
</mapper>

add.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="/sb/js/jquery-1.8.3.js"></script>
</head>
<body>
<center>
  <h1>部门添加</h1>
  <table>
    <tbody>
    <tr>
      <td>部门名字</td><td><input  id="dname" type="text"></td>
    </tr>
    <tr>
      <td>部门位置</td><td><input id="loc" type="text"></td>
    </tr>
    <tr>
      <td colspan="2" align="center"><input onclick="insertNews()" type="button" value="添加"></td>
    </tr>
    </tbody>
  </table>
</center>
<script>
    //添加按钮
    function insertNews() {
        var dname = $("#dname").val();
        var loc = $("#loc").val();
        $.get(
            "/sb/dept/insertDept",
            {dname:dname,loc:loc},
            function(data) {
                alert(data.msg);
                location.href="list.html";
            },
            "json"
        );
    }
</script>
</body>
</html>

list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/sb/js/jquery-1.8.3.js"></script>
    <script>
        $(function(){
            $.ajax({
                url:"/sb/dept/list",//请求地址
                dataType:"json",//返回值格式
                success:function(data){
                    if(data!=''){
                        var tempTrs="";
                        for (var i = 0; i < data.length; i++) {
                            var obj = data[i];
                            tempTrs+="<tr><td>"+obj.DEPTNO+"<td></td><td>"+obj.DNAME+"</td><td>"+obj.LOC+"</td>" +
                                "<td><a href='update.html?deptNo="+obj.DEPTNO+"'&dname="+obj.DNAME+"><input value='更新' type='button'></a>&nbsp; " +
                                "<input value='删除' type='button' οnclick='deleteOne("+obj.DEPTNO+")'> </td></tr>";
                        }
                        $("#tbodyA").append(tempTrs);
                    }
                }
            });
        });

    </script>
</head>
<body>
<center>
    <h1>部门列表</h1>
    <input type="button" value="添加" onclick="insert()">
    <table border="1" width="600px;">
        <thead><td>名称</td><td>位置</td><td>操作</td></thead>
        <tbody id="tbodyA"></tbody>
    </table>
</center>
<script>
    //添加按钮
    function insert() {
        location.href="/sb/html/add.html";
    }
    function deleteOne(deptNo) {
        if(confirm("确定删除吗?")){
            $.get(
                "/sb/dept/deleteOne",
                {deptNo:deptNo},
                function(data) {
                    alert(data.msg);
                    location.href="/sb/html/list.html";
                },
                "json"
            );
        }
    }
</script>
</body>
</html>

update.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/sb/js/jquery-1.8.3.js"></script>
    <script>
        $(function(){
            $.ajax({
                url:"/sb/dept/list",//请求地址
                dataType:"json",//返回值格式
                success:function(data){
                    if(data!=''){
                        var tempTrs="";
                        for (var i = 0; i < data.length; i++) {
                            var obj = data[i];
                            tempTrs+="<tr><td>"+obj.DEPTNO+"<td></td><td>"+obj.DNAME+"</td><td>"+obj.LOC+"</td>" +
                                "<td><a href='update.html?deptNo="+obj.DEPTNO+"'&dname="+obj.DNAME+"><input value='更新' type='button'></a>&nbsp; " +
                                "<input value='删除' type='button' οnclick='deleteOne("+obj.DEPTNO+")'> </td></tr>";
                        }
                        $("#tbodyA").append(tempTrs);
                    }
                }
            });
        });

    </script>
</head>
<body>
<center>
    <h1>部门列表</h1>
    <input type="button" value="添加" onclick="insert()">
    <table border="1" width="600px;">
        <thead><td>名称</td><td>位置</td><td>操作</td></thead>
        <tbody id="tbodyA"></tbody>
    </table>
</center>
<script>
    //添加按钮
    function insert() {
        location.href="/sb/html/add.html";
    }
    function deleteOne(deptNo) {
        if(confirm("确定删除吗?")){
            $.get(
                "/sb/dept/deleteOne",
                {deptNo:deptNo},
                function(data) {
                    alert(data.msg);
                    location.href="/sb/html/list.html";
                },
                "json"
            );
        }
    }
</script>
</body>
</html>

PageUtil.java

package com.aaa.sb.util;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * className:PageUtil
 * discription:
 * author:luRuiHua
 * createTime:2018-11-19 11:48
 */
public class PageUtil {
    //分页的要素
    private int pageNo;//页码(第几页)
    private int pageSize;//每页显示数量
    private int totalSize;//总条数
    //临时变量
    private String url;//请求的url
    private String pageString;//拼接后的分页字符串

    /**
     * 构造
     * @param pageNo
     * @param pageSize
     * @param totalSize
     * @param request  可以用来获取当前请求的地址和所有的请求参数
     */
    public PageUtil(int pageNo, int pageSize, int totalSize, HttpServletRequest request){
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        this.totalSize = totalSize;
        //获取本次请求的url(从项目名称开始)
        url = request.getRequestURI()+"?";  //  /web20180918/jsp/page/page3.jsp?pageNo=2&dname=内&id=&aa=11&bb=22
        //getParameterNames获取所有请求中带的参数的名称  pageNo=2&dname=内&id=   getParameterNames获取到结果为:
        Enumeration<String> parameterNames = request.getParameterNames();//获取参数名称集合  [pageNo,dname,id]
        while(parameterNames.hasMoreElements()){//判断有没有下一个元素
            String parameterName = parameterNames.nextElement();//第一次取到的pageNo
            //!"pageNo".equals(parameterName)  每次请求,pageNo都在变化,所以下面拼接pageString一直会带上
            if(!"pageNo".equals(parameterName)){
                //charAt 得到字符串某个位置的上的字符
                if(url.charAt(url.length()-1)=='?'){//判断请求的最后位置是否是?
                    url+=parameterName+"="+request.getParameter(parameterName);// /web20180918/jsp/page/page3.jsp?dname=内
                }else{
                    url+="&"+parameterName+"="+request.getParameter(parameterName);///web20180918/jsp/page/page3.jsp?dname=内&id=&&aa=11&
                }
            }
        }
        //为了下面拼接简单
        if(url.charAt(url.length()-1)!='?'){
            url+="&";
        }
    }
    // url =/web20180918/jsp/page/page3.jsp?dname=内&id=&&aa=11&
    /**
     * 拼装分页字符串
     * @return
     */
    public String getPageString(){
        //计算总页数
        int pageCount = totalSize%pageSize==0?totalSize/pageSize:totalSize/pageSize+1;
        StringBuffer stringBuffer = new StringBuffer();
        //上一页不能小于1
        if(pageNo<1){
            pageNo = 1;
        }
        if(pageNo>1){//不是第一页
            stringBuffer.append("<a href='"+url+"pageNo=1'>首页</a>&nbsp;<a href='"+url+"pageNo="+(pageNo-1)+"'>上一页</a>");
        }else{
            stringBuffer.append("首页&nbsp;上一页");
        }
        stringBuffer.append("&nbsp;");
        //不能大于最大页
        if(pageNo>pageCount){
            pageNo=pageCount;
        }
        if(pageNo<pageCount){//不是最大页(尾页)
            stringBuffer.append("<a href='"+url+"pageNo="+(pageNo+1)+"'>下一页</a>&nbsp;<a href='"+url+"pageNo="+pageCount+"'>尾页</a>");
        }else{
            stringBuffer.append("下一页&nbsp;尾页");
        }
        stringBuffer.append("&nbsp;");
        //拼装下拉第几页                                                                                                                                                                                //this.value  select元素选中值
        stringBuffer.append("第<select οnchange=\"javascript:window.location.href='"+url+"pageNo='+this.value\">"); //为select添加onchange事件,能选择自定义页数
        for(int i=1;i<=pageCount;i++){
            if(pageNo==i){//如果当前页码(第几页)和i相等,让option被选中 selected='selected'
                stringBuffer.append("<option value='"+i+"' selected='selected'>"+i+"</option>");
            }else{
                stringBuffer.append("<option value='"+i+"'>"+i+"</option>");
            }
        }
        stringBuffer.append("</select>页&nbsp;共"+totalSize+"条&nbsp;"+pageCount+"页");
        return stringBuffer.toString();
    }
}

展开阅读全文

没有更多推荐了,返回首页