SSM之Mybatis对数据库的查询以及批量操作

来源:互联网 发布:公务员 紧缺职位 知乎 编辑:程序博客网 时间:2024/05/24 06:50

这篇文章是在我的SpringMVC前后端数据交互基础上把数据库环节打通,主要涉及mybatis的查询(传多个参数),批量删除,新增,修改,数据库是MySQL,注释很详细,直接看代码即可:

JSP

[javascript] view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3.     String path = request.getContextPath();  
  4.     String basePath = request.getScheme() + "://"  
  5.             + request.getServerName() + ":" + request.getServerPort()  
  6.             + path + "/";  
  7. %>  
  8.   
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  10. <html>  
  11. <head>  
  12.   
  13.   
  14. <title>mybatis测试页面</title>  
  15.   
  16. <script type="text/javascript"  
  17.     src="${pageContext.request.contextPath}/static/jquery/jquery-1.9.1.min.js"></script>  
  18. <script  
  19.     src="${pageContext.request.contextPath}/static/bootstrap-3.3.5/js/bootstrap.min.js"></script>  
  20. <link rel="stylesheet"  
  21.     href="${pageContext.request.contextPath}/static/bootstrap-3.3.5/css/bootstrap-theme.css"></link>  
  22. <link rel="stylesheet"  
  23.     href="${pageContext.request.contextPath}/static/bootstrap-3.3.5/css/bootstrap.css"  
  24.     type="text/css"></link>  
  25. <link rel="stylesheet"  
  26.     href="${pageContext.request.contextPath}/static/bootstrap-3.3.5/css/bootstrap.min.css"  
  27.     type="text/css"></link>  
  28. <script type="text/javascript">  
  29.     $(document).ready(function() {  
  30.         //   
  31.     });  
  32. </script>  
  33.   
  34. </head>  
  35.   
  36. <body>  
  37.     <br />  
  38.     <button type="button" onclick="test()">发送按钮</button>  
  39.     <p></p>  
  40.     <p>-----------1.条件(模糊)查询,2.一对一,一对多,多对多查询,2.批量删除,批量修改,批量新增,4.分页查询------------  
  41.     <p>  
  42.     <p>--------------------------------------------------------------------------------------------------------------------------------------------------</p>  
  43.     <p>查询结果集------:</p>  
  44.     <p id="data"></p>  
  45.     <p>---批量删除---</p>  
  46.     <div>  
  47.         <!-- 复选框,批量删除demo演示-->  
  48.         <label class="checkbox-inline"> <input type="checkbox" name="deleteCheckBox"  
  49.             id="inlineCheckbox1" value="11"> 选项 1  
  50.         </label> <label class="checkbox-inline"> <input type="CheckBox" name="deleteCheckBox"  
  51.             id="inlineCheckbox2" value="22"> 选项 2  
  52.         </label> <label class="checkbox-inline"> <input type="CheckBox" name="deleteCheckBox"  
  53.             id="inlineCheckbox3" value="33"> 选项 3  
  54.     </div>  
  55.   
  56.     <!-- 创建表脚本 -->  
  57.     <!--CREATE TABLE users (  
  58.   id int(5) NOT NULL auto_increment,  
  59.   name varchar(20)NOT NULL,  
  60.   PRIMARY KEY  (`id`)  
  61. )charset utf8 collate utf8_general_ci;  -->  
  62.     <script>  
  63.         function test() {  
  64.   
  65.             //单个参数查询  
  66.             /*  $.ajax({ 
  67.                     type : 'post', 
  68.                     url : "${pageContext.request.contextPath}/mybatis/queryByAge", 
  69.                     data:{age:"28"}, 
  70.                     dataType : "json", 
  71.                     success : function(data) {   
  72.                         console.log(data); 
  73.                         //JSON.stringify(data) 
  74.                         $("#data").text(JSON.stringify(data)); 
  75.                     }, 
  76.                     error : function() { 
  77.                         alert("查询失败"); 
  78.                     } 
  79.                 }); */  
  80.   
  81.             //多个参数查询  
  82.             //1.用注解  
  83.             /*  $.ajax({ 
  84.                     type : 'post', 
  85.                     url : "${pageContext.request.contextPath}/mybatis/queryEmp", 
  86.                     data:{queryAge:"28",queryNme:"李大嘴",deptno:"20"}, 
  87.                     dataType : "json", 
  88.                     success : function(data) {   
  89.                         console.log(data); 
  90.                         $("#data").text(JSON.stringify(data)); 
  91.                     }, 
  92.                     error : function() { 
  93.                         alert("查询失败"); 
  94.                     } 
  95.                 }); */  
  96.   
  97.             //2.用map  
  98.             /* $.ajax({ 
  99.                 type : 'post', 
  100.                 url : "${pageContext.request.contextPath}/mybatis/queryEmpWithMapParam", 
  101.                 data:{queryAge:"28",queryNme:"李大嘴",deptno:"20"}, 
  102.                 dataType : "json", 
  103.                 success : function(data) {   
  104.                     console.log(data); 
  105.                     $("#data").text(JSON.stringify(data)); 
  106.                 }, 
  107.                 error : function() { 
  108.                     alert("查询失败"); 
  109.                 } 
  110.             }); 
  111.              */  
  112.             //插入数据,主键自增  
  113.             /* var jsonObj = { 
  114.                 "empAge" : "111", 
  115.                 "empName" : "卡丽熙", 
  116.                 "deptNo" : "12138" 
  117.             }; 
  118.             $.ajax({ 
  119.                 type : 'post', 
  120.                 url : '${pageContext.request.contextPath }/mybatis/addEmp', 
  121.                 contentType : 'application/json;charset=utf-8',//指定为json类型,这个属性是配合注解@RequestBody使用的 
  122.                 //数据格式是json串 
  123.                 data : JSON.stringify(jsonObj), 
  124.                 dataType : "json", 
  125.                 success : function(data) {//返回json结果 
  126.                     console.log(data)//插入成功打印数字 1  
  127.                     alert("成功"); 
  128.                 } 
  129.             }); */  
  130.               
  131.             //批量删除数据  
  132.             /* var checkBoxArray=[]; 
  133.             $("input[name='deleteCheckBox']:checked").each(function () { 
  134.                 checkBoxArray.push(this.value) 
  135.             }); 
  136.             $.ajax({ 
  137.                 type : 'post', 
  138.                 url : '${pageContext.request.contextPath }/mybatis/deleteBatch', 
  139.                 traditional : true,//注意,必须要有个设置否则传递数组报400错误。默认为false深度序列化,在此改为true 
  140.                 data : { 
  141.                     "array" : checkBoxArray 
  142.                 }, 
  143.                 success : function(data) {//返回json结果 
  144.                     console.log(data)//插入成功打印数字 1  
  145.                     alert("批量删除成功"); 
  146.                 }, 
  147.                 error : function() { 
  148.                     alert("查询失败"); 
  149.                 } 
  150.             }); */  
  151.               
  152.               
  153.             //批量新增  
  154.             /* var empObjList=[]; 
  155.             var emp1={ 
  156.                     "empAge" : "1111", 
  157.                     "empName" : "布兰", 
  158.                     "deptNo" : "1" 
  159.                 }; 
  160.             var emp2={ 
  161.                     "empAge" : "2222", 
  162.                     "empName" : "艾丽娅", 
  163.                     "deptNo" : "2" 
  164.                 }; 
  165.             var emp3={ 
  166.                     "empAge" : "3333", 
  167.                     "empName" : "罗伯", 
  168.                     "deptNo" : "3" 
  169.                 }  
  170.             empObjList.push(emp1); 
  171.             empObjList.push(emp2); 
  172.             empObjList.push(emp3); 
  173.             $ 
  174.                     .ajax({ 
  175.                         type : 'post', 
  176.                         url : '${pageContext.request.contextPath }/mybatis/addEmpByBatch', 
  177.                         contentType : 'application/json;charset=utf-8',//指定为json类型 
  178.                         //数据格式是json串,多个对象用[]包装 
  179.                         data : JSON.stringify(empObjList), 
  180.                         success : function(data) { 
  181.                             console.log(data);  
  182.                             alert("批量新增成功"); 
  183.                         }, 
  184.                         error : function() { 
  185.                             alert("失败"); 
  186.                         } 
  187.                     }); */  
  188.                       
  189.             //批量修改  
  190.             var empObjList=[];  
  191.             var emp1={  
  192.                     "empAge" : "15",  
  193.                     "empName" : "布兰update",  
  194.                     "deptNo" : "1"  
  195.                 };  
  196.             var emp2={  
  197.                     "empAge" : "19",  
  198.                     "empName" : "艾丽娅update",  
  199.                     "deptNo" : "2"  
  200.                 };  
  201.             var emp3={  
  202.                     "empAge" : "26",  
  203.                     "empName" : "罗伯update",  
  204.                     "deptNo" : "3"  
  205.                 }   
  206.             empObjList.push(emp1);  
  207.             empObjList.push(emp2);  
  208.             empObjList.push(emp3);  
  209.             $  
  210.                     .ajax({  
  211.                         type : 'post',  
  212.                         url : '${pageContext.request.contextPath }/mybatis/updateEmpByBatch',  
  213.                         contentType : 'application/json;charset=utf-8',//指定为json类型  
  214.                         //数据格式是json串,多个对象用[]包装  
  215.                         data : JSON.stringify(empObjList),  
  216.                         success : function(data) {  
  217.                             console.log(data.toString());   
  218.                             alert("批量修改成功");  
  219.                         },  
  220.                         error : function() {  
  221.                             alert("失败");  
  222.                         }  
  223.                     });  
  224.         }  
  225.     </script>  
  226. </body>  
  227. </html>  

controller

[java] view plain copy
  1. package com.wonders.controller;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import org.springframework.beans.factory.annotation.Autowired;  
  9. import org.springframework.stereotype.Controller;  
  10. import org.springframework.web.bind.annotation.RequestBody;  
  11. import org.springframework.web.bind.annotation.RequestMapping;  
  12. import org.springframework.web.bind.annotation.RequestParam;  
  13. import org.springframework.web.bind.annotation.ResponseBody;  
  14. import org.springframework.web.servlet.ModelAndView;  
  15.   
  16. import com.wonders.entity.Emp;  
  17. import com.wonders.entity.User;  
  18. import com.wonders.service.EmpService;  
  19. import com.wonders.service.UserService;  
  20. /** 
  21.  * AJAX+mybatis+mysql各种情况下查询 
  22.  * 传数组批量 
  23.  * 多个参数封装 (map @param) 
  24.  * @author Administrator 
  25.  * 
  26.  */  
  27. @Controller  
  28. @RequestMapping("/mybatis")  
  29. public class MyBatisController {  
  30.     @Autowired  
  31.     private EmpService empService;  
  32.     //http://127.0.0.1:8080/ssmmaven/mybatis/showView  
  33.     @RequestMapping("/showView")    
  34.     public ModelAndView showView(){      
  35.         ModelAndView mv = new ModelAndView();   
  36.         mv.setViewName("mybatis");  
  37.         return mv;    
  38.     }  
  39.     ///////////////////////////////////////////////////////////////////////////  
  40.     /** 
  41.      * 单个参数查询 
  42.      * @param age 
  43.      * @return 
  44.      */  
  45.     @RequestMapping("/queryByAge")  
  46.     public @ResponseBody List<Emp> queryByAge(String age){  
  47.         return empService.selectEmpByAge(age);  
  48.     }  
  49.     ////////////////////////////////////////////////////////////////////////////////  
  50.     /** 
  51.      * 多个参数查询 
  52.      * 1.注解 
  53.      */  
  54.     @RequestMapping("/queryEmp")//  
  55.     public @ResponseBody Emp queryEmp(String queryAge, String queryNme,Integer deptno){  
  56.         Emp emp=empService.selectEmp(queryAge, queryNme, deptno);  
  57.         System.out.println("controller:"+emp);  
  58.         return emp;  
  59.     }  
  60.     /** 
  61.      * 2.多个参数用map封装 
  62.      */  
  63.     @RequestMapping("/queryEmpWithMapParam")//  
  64.     public @ResponseBody Emp queryEmpWithMapParam(String queryAge, String queryNme,Integer deptno){  
  65.         Map<String,Object> map=new HashMap<String,Object>();  
  66.         map.put("age", queryAge);  
  67.         map.put("name", queryNme);  
  68.         map.put("deptno", deptno);  
  69.         Emp emp=empService.queryEmpWithMapParam(map);  
  70.         System.out.println("controller:"+emp);  
  71.         return emp;  
  72.     }  
  73.     /** 
  74.      * 插入数据 主键自增,更新操作同理 
  75.      */  
  76.     @RequestMapping("/addEmp")//  
  77.     public @ResponseBody Integer addEmp(@RequestBody Emp emp){  
  78.           
  79.         return empService.addEmp(emp);  
  80.     }     
  81.     /** 
  82.      * 批量删除 
  83.      */  
  84.     @SuppressWarnings("null")  
  85.     @RequestMapping(value="/deleteBatch")  
  86.     public @ResponseBody Integer  deleteBatch(@RequestParam(value="array") Integer[] array){    
  87.          if (array == null && array.length <= 0) {  
  88.                 return 0;  
  89.             }  
  90.         return empService.deleteEmpBatch(array);  
  91.     }  
  92.     /** 
  93.      * 批量新增 
  94.      */  
  95.     @RequestMapping(value="/addEmpByBatch")  
  96.     public @ResponseBody Integer addEmpByBatch(@RequestBody ArrayList<Emp> emps){    
  97.         return empService.addEmpByBatch(emps);  
  98.     }  
  99.     /** 
  100.      * 批量更新  jdbc.properties文件添加----allowMultiQueries=true 
  101.      */  
  102.     @RequestMapping(value="/updateEmpByBatch")  
  103.     public @ResponseBody Integer updateEmpByBatch(@RequestBody ArrayList<Emp> emps){    
  104.         return empService.updateEmpByBatch(emps);  
  105.     }  
  106. }  
直接看mapper和mapper.xml

[java] view plain copy
  1. package com.wonders.dao;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import org.apache.ibatis.annotations.Param;  
  7.   
  8. import com.wonders.entity.Emp;  
  9.   
  10. public interface EmpMapper {  
  11.     //单个参数查询  
  12.     public List<Emp> selectEmpByAge(String age);  
  13.     //多个参数查询用@Param注解传参数  
  14.     public Emp selectEmp(@Param("age") String queryAge,@Param("name") String queryNme,@Param("deptno") Integer deptno);  
  15.     //多个参数查询用Map封装  
  16.     public Emp queryEmpWithMapParam(Map<String,Object> map);  
  17.     //插入数据主键自增  
  18.     public int addEmp(Emp emp);  
  19.     //checkBox批量删除  
  20.     public int deleteEmpBatch(Integer[] array);  
  21.     //批量新增  
  22.     public int addEmpByBatch(List<Emp> emps);  
  23.     //批量更新  
  24.     public int updateEmpByBatch(List<Emp> emps);   
  25. }  

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"    
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  4. <mapper namespace="com.wonders.dao.EmpMapper">  
  5.     <resultMap id="EmpResultMap" type="com.wonders.entity.Emp">  
  6.         <id column="ID" property="empId" jdbcType="INTEGER" />  
  7.         <result column="NAME" property="empName" jdbcType="CHAR" />  
  8.         <result column="AGE" property="empAge" jdbcType="CHAR" />  
  9.         <result column="DEPTNO" property="deptNo" jdbcType="INTEGER" />  
  10.     </resultMap>  
  11.     <!-- 单个参数查询 -->  
  12.     <select id="selectEmpByAge" parameterType="String" resultMap="EmpResultMap">  
  13.         SELECT * FROM EMP WHERE AGE = #{age}  
  14.     </select>  
  15.     <!--多个参数查询@Param注解封装-->  
  16.     <select id="selectEmp"  resultMap="EmpResultMap">  
  17.         SELECT * FROM EMP WHERE AGE = #{age,jdbcType=VARCHAR} AND NAME=#{name,jdbcType=VARCHAR}  AND DEPTNO=#{deptno,jdbcType=DECIMAL}  
  18.     </select>  
  19.     <!--多个参数查询map封装,直接用key就可以取值,parameterType="map"不写也可以-->  
  20.     <select id="queryEmpWithMapParam" parameterType="map" resultMap="EmpResultMap">  
  21.         SELECT * FROM EMP WHERE AGE = #{age,jdbcType=VARCHAR} AND NAME=#{name,jdbcType=VARCHAR}  AND DEPTNO=#{deptno,jdbcType=DECIMAL}  
  22.     </select>  
  23.     <!--插入数据,主键自增  -->  
  24.     <insert id="addEmp" parameterType="com.wonders.entity.Emp"  
  25.         useGeneratedKeys="true">  
  26.         insert into EMP(NAME,AGE,DEPTNO)   
  27.         values(#{empName},#{empAge},#{deptNo})  
  28.     </insert>  
  29.     <!-- 批量删除 -->  
  30.     <delete id="deleteEmpBatch" parameterType="Integer">  
  31.         delete from EMP where   
  32.         <foreach item="check_value" collection="array" open="ID in ("  
  33.             separator="," close=")">  
  34.             #{check_value}  
  35.         </foreach>  
  36.     </delete>  
  37.     <!-- 批量新增-->  
  38.     <insert id="addEmpByBatch" parameterType="java.util.List" useGeneratedKeys="true">  
  39.     insert into EMP (NAME,AGE,DEPTNO)  
  40.     values   
  41.     <foreach collection="list" item="item" index="index" separator="," >  
  42.         (#{item.empName},#{item.empAge},#{item.deptNo})  
  43.     </foreach>  
  44.     </insert>  
  45.     <!-- 批量更新 -->  
  46.     <update id="updateEmpByBatch"  parameterType="java.util.List">    
  47.     <foreach collection="list" item="item" index="index" separator=";">  
  48.        update EMP  
  49.        <set >  
  50.           <if test="item.empName != null" >  
  51.             NAME = #{item.empName,jdbcType=VARCHAR},  
  52.           </if>  
  53.           <if test="item.empAge != null" >  
  54.             AGE = #{item.empAge,jdbcType=VARCHAR},  
  55.           </if>  
  56.         </set>  
  57.         where DEPTNO = #{item.deptNo,jdbcType=INTEGER}  
  58.     </foreach>         
  59. </update>  
  60.   
  61. </mapper>  


数据库配置文件注意的地方:

jdbc_url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true



转载地址:http://blog.csdn.net/huangcsdnjava/article/details/78055372




原创粉丝点击