mcv实现通用的增删改查

Posted huxiaocong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mcv实现通用的增删改查相关的知识,希望对你有一定的参考价值。

在mvc框架和前一次通用分页的基础上,我们可以完善一下,把它做成一个通用的增删改查

话不多说直接上代码:

先创建一个与数据库表名对应的实体类Book:

package com.entity;

public class Book 
    private int bid;
    private String bname;
    private float price;

    @Override
    public String toString() 
        return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
    

    public int getBid() 
        return bid;
    

    public void setBid(int bid) 
        this.bid = bid;
    

    public String getBname() 
        return bname;
    

    public void setBname(String bname) 
        this.bname = bname;
    

    public float getPrice() 
        return price;
    

    public void setPrice(float price) 
        this.price = price;
    

    public Book(int bid, String bname, float price) 
        super();
        this.bid = bid;
        this.bname = bname;
        this.price = price;
    

    public Book() 
        super();
    

创建一个执行sql语句的BaseDao:

package com.dao;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.util.DBAccess;
import com.util.PageBean;

/**
 * T代表你要对哪个实体类对应表进行查询
 * 
 * @author Administrator
 *
 * @param <T>
 */
public class BaseDao<T> 
 
    /**
     * 
     * @param sql 查询不同的实体类,那么对应的sql不同,所以需要传递 
     * @param clz  生产出不同的实体类对应的实例,然后装进list容器中返回
     * @param pageBean  决定是否分页
     * @return
     * @throws Exception 
     */
    public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws Exception
        
        Connection con=DBAccess.getConnection();
        PreparedStatement ps=null;
        ResultSet rs=null;
       if(pageBean!=null&&pageBean.isPagination()) 
           //需要分页(算符合条件的总记录数)
           String countSql=getCountSql(sql);
           ps=con.prepareStatement(countSql);
           rs=ps.executeQuery();
           if(rs.next()) 
               pageBean.setTotal(rs.getLong(1)+"");
           
           //查询出符合条件的结果集
           String pageSql=getpageSql(sql,pageBean);
           ps=con.prepareStatement(pageSql);
           rs=ps.executeQuery();
           
       else 
           ps=con.prepareStatement(sql);
           rs=ps.executeQuery();
       
        
        
        
        
        List<T> list=new ArrayList<T>();
        T t;
        while(rs.next()) 
        /**
         * 1.实例化一个book对象(该对象是空的)
         * 2.取book的所有的属性,然后给其赋值
         *  2.1获取所有属性对象
         *  2.2给属性对象赋值
         * 3.赋完值的book对象装进list容器中
         */
        t=(T)clz.newInstance();
            Field[] fields=clz.getDeclaredFields();
            for (Field field : fields) 
                field.setAccessible(true);
                field.set(t, rs.getObject(field.getName()));
            
            list.add(t);
        
        DBAccess.close(con, ps, rs);
        return list;
    
   
    /**
     * 利用原生sql拼接出符合条件的结果集的sql
     * @param sql
     * @param pageBean
     * @return
     */
    private String getpageSql(String sql, PageBean pageBean) 
        // TODO Auto-generated method stub
        return sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows();
    

    /**
     * 获取符合条件的总记录数的sql
     * @param sql
     * @return
     */
    private String getCountSql(String sql) 
      
        
        return "SELECT COUNT(1)FROM ("+sql+")t";
    
    
    /**
     * 
     * @param sql 决定增删改的一种
     * @param attrs 决定?位置 new String[]"bid,"bname"
     * @param t 要操作的实体
     * @return
     * @throws Exception 
     * @throws NoSuchFieldException 
     */
    public int executeUpdate (String sql,String[] attrs,T t) throws NoSuchFieldException, Exception 
        Connection con=DBAccess.getConnection();
        PreparedStatement ps=con.prepareStatement(sql);
        for(int i=1;i<=attrs.length;i++) 
        Field f=t.getClass().getDeclaredField(attrs[i-1]);
        f.setAccessible(true);
        ps.setObject(i, f.get(t));
        
        int num=ps.executeUpdate();
        DBAccess.close(con, ps, null);
        
        return num;
    
     
    

 

创建一个提供sql语句的BookDao:

package com.dao;

import java.util.List;

import com.entity.Book;
import com.util.BaseDao;
import com.util.PageBean;
import com.util.StringUtils;

public class BookDao extends BaseDao<Book> 
    /**
     * 查询所有
     * 
     * @param book
     * @param pageBean
     * @return
     * @throws Exception
     */
    public List<Book> list(Book book, PageBean pageBean) throws Exception 
        String sql = "select * from t_mvc_book where true";
        String bname = book.getBname();
        int bid = book.getBid();
        if (StringUtils.isNotBlank(bname)) 
            sql += " and bname like ‘%" + bname + "%‘";
        
        if (bid != 0) 
            sql += " and bid=" + bid;
        
        return super.executeQuery(sql, Book.class, pageBean);

    

    /**
     * 修改
     * 
     * @param book
     * @return
     * @throws Exception
     * @throws NoSuchFieldException
     */
    public int upde(Book book) throws NoSuchFieldException, Exception 
        String sql = "update t_mvc_book set bname=?,price=? where bid=?";
        return super.executeUpdate(sql, new String[]  "bname", "price", "bid" , book);
    

    /**
     * 新增
     * 
     * @param book
     * @return
     * @throws Exception
     * @throws NoSuchFieldException
     */
    public int add(Book book) throws NoSuchFieldException, Exception 
        String sql = "insert into t_mvc_book values(?,?,?)";
        System.out.println(sql);
        return super.executeUpdate(sql, new String[]  "bid", "bname", "price" , book);
    

    /**
     * 删除
     * 
     * @param book
     * @return
     * @throws Exception
     * @throws NoSuchFieldException
     */
    public int del(Book book) throws NoSuchFieldException, Exception 
        String sql = "delete from t_mvc_book where bid=?";

        return super.executeUpdate(sql, new String[]  "bid" , book);
    

执行类BookAction:

package com.web;

import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.BookDao;
import com.entity.Book;
import com.framework.ActionSupport;
import com.framework.ModelDrivern;
import com.util.PageBean;

public class BookAction extends ActionSupport implements ModelDrivern<Book> 
    private Book book = new Book();
    private BookDao bookdao = new BookDao();

    /**
     * 分页查询
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    public String list(HttpServletRequest request, HttpServletResponse response) throws Exception 
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        List<Book> list = this.bookdao.list(book, pageBean);
        request.setAttribute("booklist", list);
        request.setAttribute("pagebean", pageBean);
        return "list";
    

    /**
     * 
     * 跳转到增加或修改页面
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String preSave(HttpServletRequest request, HttpServletResponse response) 
        // bid的类型是int类型,而int类型的默认值是0,如果jsp未传递bid的参数值那么bid=0;
        if (book.getBid() == 0) 
            System.out.println("增加逻辑");

         else 
            // 修改数据回显
            Book b;
            try 
                b = this.bookdao.list(book, null).get(0);
                request.setAttribute("book", b);
             catch (Exception e) 
                // TODO Auto-generated catch block
                e.printStackTrace();
            

        
        return "edit";

    

    /**
     * 新增
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String add(HttpServletRequest request, HttpServletResponse response) throws Exception 
        // 新增完了之后刷新页面
        this.bookdao.add(book);
        return "tolist";

    

    /**
     * 修改
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String upde(HttpServletRequest request, HttpServletResponse response) throws Exception 
        // 修改完了之后刷新页面
        this.bookdao.upde(book);
        return "tolist";

    
    /**
     * 删除
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String del(HttpServletRequest request, HttpServletResponse response) throws Exception 
        // 删除之后刷新页面
        this.bookdao.del(book);
        return "tolist";
    

    @Override
    public Book getModel() 
        // TODO Auto-generated method stub
        return book;
    

xml文件配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>MVC</display-name>
 
  <servlet>
  <servlet-name>DispatcherServlet</servlet-name>
  <servlet-class>com.framework.DispatcherServlet</servlet-class>
  <init-param>
  <param-name>xmlPath</param-name>
  <param-value>/mvc.xml</param-value>
  </init-param>
  </servlet>
  <servlet-mapping>
  <servlet-name>DispatcherServlet</servlet-name>
  <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

jsp主页面页面book.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@page isELIgnored="false" %>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@taglib prefix="m"  uri="/MyJSP"%>
<!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">
<title>Insert title here</title>
</head>
<body>
<h2>小说目录</h2>
    <br>
<c:if test="$empty booklist ">
    <jsp:forward page="book.action?menthodName=list"></jsp:forward>
</c:if>
    <form action="$pageContext.request.contextPath/book.action?menthodName=list"
        method="post">
        书名:<input type="text" name="bname"> <input type="submit"
            value="确定">
            
    </form>
    <a href="$pageContext.request.contextPath/book.action?menthodName=preSave">新增</a>
    
    <table border="1" width="100%">
        <tr>
            <td>编号</td>
            <td>名称</td>
            <td>价格</td>
            <td>操作</td>
        </tr>
        <c:forEach items="$booklist " var="b">
            <tr>
                <td>$b.bid </td>
                <td>$b.bname </td>
                <td>$b.price </td>
                <td><a href="$pageContext.request.contextPath/book.action?menthodName=preSave&&bid=$b.bid">修改</a>
                </td>
                <td><a href="$pageContext.request.contextPath/book.action?menthodName=del&&bid=$b.bid">删除</a>
                </td>
            </tr>
        </c:forEach>
    </table>
<m:page bean="$pagebean "></m:page> 

    
</body>
</html>

增,改通用的bookList.lsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="m" uri="/MyJSP"%>
<!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">
<title>Insert title here</title>
</head>
<body>
    <h2>小说目录</h2>
    <br>
    <c:if test="$empty booklist ">
        <jsp:forward page="book.action?menthodName=list"></jsp:forward>
    </c:if>
    <form
        action="$pageContext.request.contextPath/book.action?menthodName=list"
        method="post">
        书名:<input type="text" name="bname"> <input type="submit"
            value="确定">

    </form>
    <a
        href="$pageContext.request.contextPath/book.action?menthodName=preSave">新增</a>

    <table border="1" width="100%">
        <tr>
            <td>编号</td>
            <td>名称</td>
            <td>价格</td>
            <td>操作</td>
        </tr>
        <c:forEach items="$booklist " var="b">
            <tr>
                <td>$b.bid </td>
                <td>$b.bname </td>
                <td>$b.price </td>
                <td><a
                    href="$pageContext.request.contextPath/book.action?menthodName=preSave&&bid=$b.bid">修改</a>
                </td>
                <td><a
                    href="$pageContext.request.contextPath/book.action?menthodName=del&&bid=$b.bid">删除</a>
                </td>
            </tr>
        </c:forEach>
    </table>
    <m:page bean="$pagebean "></m:page>


</body>
</html>

效果如下:

技术图片

 

技术图片

 

以上是关于mcv实现通用的增删改查的主要内容,如果未能解决你的问题,请参考以下文章

MySQL-增删改查简易操作

MySQL-增删改查简易操作

django配置模型增删改查

MySQL基本操作--库表增删改查

通用mapper的增删改查方法 留存 备忘

库表曾删改查和存储引擎