1. 程式人生 > >SSM框架CRUD操作&批量刪除&批量追加資料(Oracle&MySQL資料庫)

SSM框架CRUD操作&批量刪除&批量追加資料(Oracle&MySQL資料庫)

SSM框架CRUD操作Demo
1、SSM開發環境搭建詳見下一章微博
2、定義起始頁,基本的超連結完成請求,詳見如圖

由於時間關係,本人將在本部落格中陸續推出高階框架階段的系列教程,現已經發布如下幾篇,如果對大家有幫助也請各位給點鼓勵吧 ,比如關注微博、頂一下或者給點評論,謝謝!

1、SSM開發環境搭建詳見下一章微博
2、定義起始頁,基本的超連結完成請求,詳見如圖

    <fieldset>
        <legend>SSM CRUD  資料庫:MySQL,請切換連線MySQL引數</legend>
        <a href
="user/queryAllUser.do">
檢視所有員工資訊</a> </fieldset>

這裡寫圖片描述

3、編寫對對應控制器Handler

@Controller
@RequestMapping("/user")
public class UserAction {
    @Autowired
    private IUserService userService;
    @RequestMapping("/queryAllUser")
    public String queryAllUser(Map<String,Object> requests){
        requests.put("users"
,userService.queryAllUser()); return "/users"; } }

4、建立service

@Service
@Transactional
public class IUserServiceImpl implements IUserService {
    @Resource
    private IUserDao userDao;

    public List<User> queryAllUser(){
        return userDao.queryAllUser();
    }
}

5、建立對應的Dao

public interface IUserDao {
    public List<User> queryAllUser();
}

6、建立MyBaits對應的SQL文

<?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.rock.trainner.dao.IUserDao">
    <sql id="userLists">
        userid,username,phone,birthday,score,typename,password,question,answer
    </sql>
    <select id="queryAllUser" resultType="User">
        select <include refid="userLists"/> from user
    </select>
</mapper>

響應的畫面效果如圖:
這裡寫圖片描述

7、下面來看看頁面效果的實現程式碼及前對對批量刪除的前端程式碼,程式碼中有註釋

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/users.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/users_hover.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-2.1.1.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        //滑鼠移動到行變色,單獨建立css類hover
        //tr:gt(0):表示獲取大於 tr index 為0 的所有tr,即不包括表頭
       /*  $("#customers tbody tr:odd").addClass("odd");
        $("#customers tbody tr:even").addClass("even"); */
        var flag=false;
        $("#customers tr:gt(0)").hover(
        function () {
            if($(this).prop("class")=="alt"){
                flag=true;
            }
            $(this).removeClass("alt");
            $(this).addClass("hover");
            },
        function () {
            if(flag){
                $(this).addClass("alt");
            }
            $(this).removeClass("hover");
            flag=false;
        });

        $("#sal").click(function(){
            /* 返回了rquest域中users這個List集合的長度(User的個數) */
            var max="${fn:length(requestScope.users) }";
            for(var i=0;i<max;i++){
                if(this.checked){
                    $("#selecters"+i).prop("checked",true);
                }
                else
                    $("#selecters"+i).prop("`checked",false);
            }
        });
        $("#del").click(function(){
            var url="deleteBatchById.do?ids=";
            var max="${fn:length(requestScope.users) }";
            var ids="";
            /* 迴圈遍歷所有的複選框 */
            for(var i=0;i<max;i++){
                if($("#selecters"+i).prop("checked")){//若這個複選框被選中狀態,那麼結果是true 否則是false、
                    ids+=$("#selecters"+i).prop("value")+",";//若複選框被選中狀態,那麼將這個複選框中的value值獲取後儲存在ids變數zhong
                }
            }
            ids=ids.substr(0,ids.length-1);
            /* alert(ids); */
            /* 
                通過jQuery的get方法發起非同步請求(ajax)請求,是以get方式發起的請求
                第一個引數:ajax請求的url是多少
                第二個引數是回撥函式:回撥函式中的第一個引數是伺服器返回來的資料,第二個引數儲存了ajaxget請求執行結果
            */
            $.get(url+ids,function(data,status){   //url=deleteBatchById.do?ids=3,66,332,11
                /* 將id屬性值是customers的table元素中的tr的行數大於0 就是除了表頭之外的所有行 remove(); */
                $("#customers tr:gt(0)").remove();
                var newRow="";
                /* [{"userid":"aa","password":"aa","username":"aa","phone":"aa","birthday":"2010-09-09","score":200,"typename":"aaa","question":"aaa","answer":"aaa"},
                 {"userid":"bb","password":"aa","username":"aa","phone":"aa","birthday":"2010-09-09","score":200,"typename":"aaa","question":"aaa","answer":"aaa"},
                 {"userid":"cc","password":"aa","username":"aa","phone":"aa","birthday":"2010-09-09","score":200,"typename":"aaa","question":"aaa","answer":"aaa"},
                 {"userid":"dd","password":"aa","username":"aa","phone":"aa","birthday":"2010-09-09","score":200,"typename":"aaa","question":"aaa","answer":"aaa"}
                 ] */
                for(var i=0;i<data.length;i++){   //data<---List<User>  [{},{},{}]     
                    var id=data[i].userid;
                    var username=data[i].username;
                    var phone=data[i].phone;
                    var birthday=data[i].birthday;
                    var score=data[i].score;
                    var typename=data[i].typename;
                    var password=data[i].password;
                    var question=data[i].question;
                    var answer=data[i].answer;
                    //alert(id+"&nbsp;"+username+"&nbsp;"+phone+"&nbsp;"+birthday);
                    if(i%2==0){
                        newRow="<tr><td>"+
                        "<input type='checkbox' id='selecters"+i+"' name='selecters' value='"+id+"'>"
                        +"</td><td>"+id+"</td><td>"+
                        "<a href='abc'>"+
                        username+
                        "</a>"+
                        "</td><td>"+phone+"</td><td>"+password+"</td><td>"+typename+"</td></tr>";
                    }
                    else{

                        newRow="<tr class='alt'><td>"+
                        "<input type='checkbox' id='selecters"+i+"' name='selecters' value='"+id+"'>"
                        +"</td><td>"+id+"</td><td>"+username+"</td><td>"+phone+"</td><td>"+password+"</td><td>"+typename+"</td></tr>";
                    }

                    $("#customers tr:last").after(newRow);
                }  
                /* 將整個頁面進行重新載入,說白了就是整個頁面重新整理一次 */
                //window.location.reload();//  reload body
            });
        });
        $("#delBody").click(function () {
            //刪除指定行(第二行)
            // $("#table3 tr:gt(0):eq(1)").remove();
            /* 刪除其它行,比如第二行之外的所有行: $("#table3 tr:gt(0):not(:eq(1))").remove(); */
            $("#customers tr:gt(0)").remove();
        });
    });
</script>
<title>Insert title here</title>
</head>
<body>
    <fieldset>
        <legend>jQuery操作table</legend>
        <a href="#" id="delBody">刪除其他行</a>
    </fieldset>
    <!-- 若使用者單擊了修改按鈕 -->
    <c:if test="${not empty requestScope.user }">
            <fieldset>
                <legend>修改【${requestScope.user.username }】的資料</legend>
                <form action="${pageContext.request.contextPath}/user/doUpdate.do">
                <div>
                    Userid:<input type="text" name="userid" value="${requestScope.user.userid }">
                </div>
                <div>
                    username:<input type="text" name="username" value="${requestScope.user.username}">
                </div>
                <div>
                    password:<input type="text" name="password" value="${requestScope.user.password }">
                </div>
                <div>
                    <input type="submit" value="修改密碼"/>
                </div>
            </form>
            </fieldset>
    </c:if>
    <c:if test="${empty requestScope.users }">
        <fieldset>
            <legend>暫時沒有資料</legend>
        </fieldset>
    </c:if>
    <c:if test="${not empty requestScope.users }">
        <fieldset>
        <legend>所有員工資訊如下</legend>
        <table id="customers">
            <tr>
                <th>
                    <input type="checkbox" id="sal" > 全選
                    <a href="#" id="del">刪除</a>
                </th>
                <th>使用者編號</th>
                <th>使用者姓名</th>
                <th>使用者電話</th>
                <th>登入密碼</th>
                <th>會員型別</th>
                <th>操作</th>
            </tr>
            <c:forEach items="${requestScope.users }" var="user" varStatus="stus">
                <c:if test="${stus.count%2 eq 0 }">
                    <tr>
                        <td>
                            <input type="checkbox" id="selecters${stus.index}" name="selecters" value="${user.userid }">
                        </td>
                        <td>${user.userid }</td>
                        <td>
                            <a href="${pageContext.request.contextPath }/user/update.do?userid=${user.userid }">${user.username }</a>
                        </td>
                        <td>${user.phone }</td>
                        <td>${user.password }</td>
                        <td>${user.typename }</td>
                        <td>
                            <a href="${pageContext.request.contextPath }/user/deleteUser.do?userid=${user.userid }">刪除</a>
                        </td>
                    </tr>
                </c:if>
                <c:if test="${stus.count%2 eq 1 }">
                    <tr class="alt">
                        <td>
                            <input type="checkbox" id="selecters${stus.index}" name="selecters" value="${user.userid }">
                        </td>
                        <td>${user.userid }</td>
                        <td>
                            <a href="${pageContext.request.contextPath }/user/update.do?userid=${user.userid }">${user.username }</a>
                        </td>
                        <td>${user.phone }</td>
                        <td>${user.password }</td>
                        <td>${user.typename }</td>
                        <td>
                            <a href="${pageContext.request.contextPath }/user/deleteUser.do?userid=${user.userid }">刪除</a>
                        </td>
                    </tr>
                </c:if>
            </c:forEach>
        </table>

    </fieldset>
    </c:if>
    <fieldset>
        <legend>新增資料</legend>
        <div>
            <form action="${pageContext.request.contextPath}/user/addUser.do">
                <div>
                    Userid:<input type="text" name="userid" >
                </div>
                <div>
                    username:<input type="text" name="username" >
                </div>
                <div>
                    password:<input type="text" name="password" >
                </div>
                <div>
                    <input type="submit" value="新增"/>
                </div>
            </form>
        </div>
    </fieldset>

</body>
</html>

8、下面來看看批量刪除對應的控制器程式碼,因為整個CRUD操作後端程式碼中最主要的就是控制器Handler及MyBatis的對映檔案了,所以這裡把對應的程式碼全部貼出,以供參考

package com.rock.trainner.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rock.trainner.entities.User;
import com.rock.trainner.services.IUserService;

@Controller
@RequestMapping("/user")
public class UserAction {
    @Autowired
    private IUserService userService;
    @RequestMapping("/queryAllUser")
    public String queryAllUser(Map<String,Object> requests){
        requests.put("users",userService.queryAllUser());
        return "/users";
    }
    @RequestMapping("/addUser")
    public ModelAndView addUser(User user){
        System.out.println("UserAction.addUser() is running.........");
        userService.addUser(user);
        /**
         * 注意:在SpringMVC中  由控制器產生響應的方式有如下三種:
         * 1、action返回一個String,   prefix+retrunValue+suffix   ----》轉發
         * 2、action返回一個ModelAndView
         * 3、若action方法想直接轉發或重定向當前請求的話,可以通過在返回的字串前加上forword: |  redirect:
         * return "forword:users.jsp"
         * ModelAndView  modelAndView=new ModelAndView("redirect:abc.jsp");
         *   
         * 若在一個action方法中將請求繼續提交給另一個action方法,那麼無需指定一級目錄(Action類上的那個@RequestMapping)
         */
        ModelAndView  modelAndView=new ModelAndView("redirect:queryAllUser.do");
        return modelAndView;
    }

    @RequestMapping("/deleteUser")
    public String deleteUser(@RequestParam("userid") String userid){
        System.out.println("UserAction.deleteUser() is running......"+userid );
        int a=userService.deleteUser(userid);
        return "redirect:queryAllUser.do";
    }
    /*@ModelAttribute
    public void update_init(@RequestParam("userid") String userid,Map<String,Object> map){
        User user=userService.queryById(userid);
        map.put("user",user);
    }*/
    @RequestMapping("/update")
    public String update(User user,Map<String,Object> map){
        System.out.println("UserAction.update() is running......"+user );
        map.put("user",userService.queryById(user.getUserid()));
        return "users";
    }
    @RequestMapping("/doUpdate")
    public String doUpdate(@ModelAttribute("user") User user){
        System.out.println("UserAction.doUpdate() is running......"+user );

        int a=userService.updateUser(user);
        return "redirect:queryAllUser.do";
    }
//  若希望SpringMVC的Handler相應回來一個Json資料話,我們可以將這些資料存放在List集合中,
//  SpringMVC的jar包中提供了專門將List集合資料轉化成json格式的物件
    @ResponseBody
    @RequestMapping("/deleteBatchById")
    public List<User> deleteBatchById(@RequestParam(value="ids") String ids,HttpServletResponse response){
        System.out.println("UserAction.deleteBatchById()............................."+ids);
        int a=userService.deleteBatchById(ids);
        return userService.queryAllUser();
    }

    @ResponseBody
    @RequestMapping("/jsonTest")
    public List<User> jsonTest(){
        List<User> all=new ArrayList<User>();
        Map<String,User> maps=new HashMap<String,User>();
        User user1=new User("aa","aa","aa","aa","2010-09-09",200,"aaa","aaa","aaa");
        User user2=new User("bb","aa","aa","aa","2010-09-09",200,"aaa","aaa","aaa");
        User user3=new User("cc","aa","aa","aa","2010-09-09",200,"aaa","aaa","aaa");
        User user4=new User("dd","aa","aa","aa","2010-09-09",200,"aaa","aaa","aaa");
        maps.put("aa",user1);
        maps.put("bb",user2);
        maps.put("cc",user3);
        maps.put("dd",user4);
        all.add(user1);
        all.add(user2);
        all.add(user3);
        all.add(user4);

        return all;
    }

    @ResponseBody
    @RequestMapping("/jsonTestMap")
    public Map<String,User> jsonTestMap(){
        List<User> all=new ArrayList<User>();
        Map<String,User> maps=new LinkedHashMap<String,User>();
        User user1=new User("aa","aa","aa","aa","2010-09-09",200,"aaa","aaa","aaa");
        User user2=new User("bb","aa","aa","aa","2010-09-09",200,"aaa","aaa","aaa");
        User user3=new User("cc","aa","aa","aa","2010-09-09",200,"aaa","aaa","aaa");
        User user4=new User("dd","aa","aa","aa","2010-09-09",200,"aaa","aaa","aaa");
        maps.put("aa",user1);
        maps.put("bb",user2);
        maps.put("cc",user3);
        maps.put("dd",user4);
        all.add(user1);
        all.add(user2);
        all.add(user3);
        all.add(user4);

        return maps;
    }

}
<?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.rock.trainner.dao.IUserDao">
    <sql id="userLists">
        userid,username,phone,birthday,score,typename,password,question,answer
    </sql>
    <select id="queryAllUser" resultType="User">
        select <include refid="userLists"/> from user
    </select>
    <select id="queryById" parameterType="String" resultType="User">
        select <include refid="userLists"/> from user where userid=#{userid}
    </select>
    <insert id="addUser" parameterType="User">
        insert into user(userid,password,username) values(#{userid},#{password},#{username})        
    </insert>
    <delete id="deleteUser" parameterType="String">
        delete from user where userid=#{id}
    </delete>
    <update id="updateUser" parameterType="User">
        update user set password=#{password} where userid=#{userid}
    </update>
    <!-- 
        MySQL中使用in完成批量刪除操作,當然你也可以使用or多條件完成,這裡為了簡化程式碼使用in完成
        foreach是MyBatis中動態SQL中的標籤,用於迴圈處理
        collection:指定被迴圈處理的集合型別    array|list
        item:臨時變數,如java中的foreach程式碼     foreach(String s:names)中的s變數的意義
        separator:分隔符
        open:開始字元
        close:結束字元
     -->
    <delete id="deleteBatchById" parameterType="String">
        delete from user where userid in
        <foreach collection="array" item="ids" separator="," open="(" close=")">
            #{ids}
        </foreach>
    </delete>
</mapper>

9、針對Oracle和MySQL資料庫的批量追加功能稍後微博奉上,或者直接聯絡我。

10、關於SSM的批量插入資料的功能實現,今天有時間整理如下,首先我們預設實驗場景,即在完成資料的批量刪除的同時將被刪除的資料存於備份表中,因為Oracle和MySQL的批量儲存的SQL文不同,所以這裡分開進行闡述。
1)、SSM框架完成批量儲存-MySQL
①,MySQL表結構如下,user是使用者表,而user_bak是user的備份表,其結構與user表一致,通過如下語句複製而來,程式碼及表結構如下:
這裡寫圖片描述

②、在刪除備詢資料時將刪除資料存於user_bak表中
批量刪除頁面效果
這裡寫圖片描述

當選中7號和8號使用者後,單擊刪除按鈕開始批量刪除,詳情見本篇部落格前部分。這裡要補充是完成批量插入功能的實現。因為實驗場景,所以這裡採用常規手段,現將被刪除的使用者資訊從資料庫中檢索出來然後再將資料儲存到備份表中

這裡寫圖片描述

userDao的saveBatchUser_MySQL程式碼如下

public int saveBatchUser_MySQL(List<User> users);

MyBatis配置MySQL批量儲存的SQL文如下
這裡寫圖片描述

2)、SSM框架完成批量儲存-Oracle
其實Oracle和MySQL批量儲存功能的差別,從程式碼角度看,主要的差別就是SQL語句不同而已
MyBatis配置Oracle批量儲存的SQL文如下
這裡寫圖片描述

資料庫效果如下
這裡寫圖片描述

至此:SSM框架CRUD操作&批量刪除&批量追加資料(Oracle&MySQL資料庫)文章的所有功能完畢,歡迎分享交流

由於時間關係,本人將在本部落格中陸續推出高階框架階段的系列教程,現已經發布如下幾篇,如果對大家有幫助也請各位給點鼓勵吧 ,比如關注微博、頂一下或者給點評論,謝謝!