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

需求:

使用新SSM来实现增删改查

步骤

第一步:看最终包结构

idea使用SpringBoot和Spring和Mybatis来实现增删改查_第1张图片

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

第二步:配置pom.xml

  • 导包springBoot支持jdk1.8以上的,所以电脑要安装jdk.1.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.0modelVersion>

  <groupId>com.aaagroupId>
  <artifactId>SpringbootMybatisDemoartifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>

  <name>SpringbootMybatisDemo Maven Webappname>
  
  <url>http://www.example.comurl>
  
  <parent>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-parentartifactId>
    <version>2.0.4.RELEASEversion>
    <relativePath/>
  parent>
  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.7maven.compiler.source>
    <maven.compiler.target>1.7maven.compiler.target>
  properties>

  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>
    
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-jdbcartifactId>
    dependency>
    <dependency>
      <groupId>org.mybatis.spring.bootgroupId>
      <artifactId>mybatis-spring-boot-starterartifactId>
      <version>1.3.2version>
    dependency>
    <dependency>
      <groupId>com.oraclegroupId>
      <artifactId>ojdbc6artifactId>
      <version>11.2.0.4.0version>
    dependency>
  dependencies>

  <build>
    <finalName>SpringbootMybatisDemofinalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-clean-pluginartifactId>
          <version>3.0.0version>
        plugin>
        
        <plugin>
          <artifactId>maven-resources-pluginartifactId>
          <version>3.0.2version>
        plugin>
        <plugin>
          <artifactId>maven-compiler-pluginartifactId>
          <version>3.7.0version>
        plugin>
        <plugin>
          <artifactId>maven-surefire-pluginartifactId>
          <version>2.20.1version>
        plugin>
        <plugin>
          <artifactId>maven-war-pluginartifactId>
          <version>3.2.0version>
        plugin>
        <plugin>
          <artifactId>maven-install-pluginartifactId>
          <version>2.5.2version>
        plugin>
        <plugin>
          <artifactId>maven-deploy-pluginartifactId>
          <version>2.8.2version>
        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



<mapper namespace="com.aaa.sb.dao.DeptDao">
    
    <select id="getList" resultType="map">
        
      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>
    
    <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


<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Titletitle>
  <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


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <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+=""+obj.DEPTNO+""+obj.DNAME+""+obj.LOC+"" +
                                "+obj.DNAME+">  " +
                                " ";
                        }
                        $("#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


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <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+=""+obj.DEPTNO+""+obj.DNAME+""+obj.LOC+"" +
                                "+obj.DNAME+">  " +
                                " ";
                        }
                        $("#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("首页 上一页");
        }else{
            stringBuffer.append("首页 上一页");
        }
        stringBuffer.append(" ");
        //不能大于最大页
        if(pageNo>pageCount){
            pageNo=pageCount;
        }
        if(pageNo<pageCount){//不是最大页(尾页)
            stringBuffer.append("下一页 尾页");
        }else{
            stringBuffer.append("下一页 尾页");
        }
        stringBuffer.append(" ");
        //拼装下拉第几页                                                                                                                                                                                //this.value  select元素选中值
        stringBuffer.append("第页 共"+totalSize+"条 "+pageCount+"页");
        return stringBuffer.toString();
    }
}

你可能感兴趣的:(springBoot)