自定义mvc的增删查改

1.思维导图

        

2.代码

package com.zking.util;

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.zking.entity.Book;
import com.zking.util.DBAccess;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;

/**
 * 所有Dao层的父类
 * 	BookDao
 * 	UserDao
 * 	OrderDao
 * 	...
 * @author Administrator
 *
 * @param <T>
 */
public class BaseDao<T> {
	
	/**
	 * 通用的增删改
	 * @param sql	具体的增删改SQL
	 * @param t		具体要操作的表对应实体类
	 * @param attrs	具体操作表的某些字段对应的实体类属性
	 * @throws SQLException 
	 */
	public void executeUpdate(String sql, T t, String[] attrs) throws Exception {
//		attrs = new String[] {"bid","bname","price"};
//		?->bid;?->bname;?->price
		Connection con = DBAccess.getConnection();
		PreparedStatement pst = con.prepareStatement(sql);
//		pst.setObject(1, book.getBid());
//		pst.setObject(2, book.getBname());
//		pst.setObject(3, book.getPrice());
		for (int i = 0; i < attrs.length; i++) {
//			attrs[0]=bid;
			Field f = t.getClass().getDeclaredField(attrs[i]);
			f.setAccessible(true);
//			f.get(t);		bid.get(book)
			pst.setObject(i+1, f.get(t));
		}
		
		pst.executeUpdate();
	}
	
	/**
	 * 通用分页查询
	 * @param sql
	 * @param clz
	 * @return
	 * @throws Exception
	 */
	public List<T> executeQuery(String sql,Class<T> clz,PageBean pageBean) throws Exception{
		List<T> list = new ArrayList<T>();
		Connection con = DBAccess.getConnection();;
		PreparedStatement pst = null;
		ResultSet rs = null;
		
		/*
		 * 是否需要分页?
		 * 	无需分页(项目中的下拉框,查询条件教员下拉框,无须分页)	
		 * 	必须分页(项目中列表类需求、订单列表、商品列表、学生列表...)
		 */
		if(pageBean != null && pageBean.isPagination()) {
//			必须分页(列表需求)
			String countSQL = getCountSQL(sql);
			pst = con.prepareStatement(countSQL);
			rs = pst.executeQuery();
			if(rs.next()) {
				pageBean.setTotal(String.valueOf(rs.getObject(1)));
			}
			
//			挪动到下面,是因为最后才处理返回的结果集
//			-- sql=SELECT * FROM t_mvc_book WHERE bname like '%圣墟%'
//			-- pageSql=sql limit (page-1)*rows,rows 	对应某一页的数据
//			-- countSql=select count(1) from (sql) t 	符合条件的总记录数
			String pageSQL = getPageSQL(sql,pageBean);//符合条件的某一页数据
			pst = con.prepareStatement(pageSQL);
			rs = pst.executeQuery();
		}else {
//			不分页(select需求)
			pst = con.prepareStatement(sql);//符合条件的所有数据
			rs = pst.executeQuery();
		}
		
		
		while (rs.next()) {
			T t = clz.newInstance();
			Field[] fields = clz.getDeclaredFields();
			for (Field f : fields) {
				f.setAccessible(true);
				f.set(t, rs.getObject(f.getName()));
			}
			list.add(t);
		}
		return list;
	}

	/**
	 * 将原生SQL转换成符合条件的总记录数countSQL
	 * @param sql
	 * @return
	 */
	private String getCountSQL(String sql) {
//		-- countSql=select count(1) from (sql) t 	符合条件的总记录数
		return "select count(1) from ("+sql+") t";
	}

	/**
	 * 将原生SQL转换成pageSQL
	 * @param sql
	 * @param pageBean
	 * @return
	 */
	private String getPageSQL(String sql,PageBean pageBean) {
//		(this.page - 1) * this.rows
//		pageSql=sql limit (page-1)*rows,rows
		return sql + " limit "+ pageBean.getStartIndex() +","+pageBean.getRows();
	}
}

 

package com.zking.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

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

public class BookDao extends BaseDao<Book>{
	/**
	 * 现状:增删改
	 * 	1.写sql
	 * 	2.建立链接
	 * 	3.预定义对象PreparedStatement
	 * 	4.设置参数
	 * 	5.执行sql
	 * 解决:
	 * 	
	 * @param book
	 * @throws Exception
	 */
//	public void add(Book book) throws Exception {
//		String sql  = "insert into t_mvc_book values(?,?,?)";
//		Connection con = DBAccess.getConnection();
//		PreparedStatement pst = con.prepareStatement(sql);
//		pst.setObject(1, book.getBid());
//		pst.setObject(2, book.getBname());
//		pst.setObject(3, book.getPrice());
//		pst.executeUpdate();
//	}
	public void add(Book book) throws Exception {
		String sql  = "insert into t_mvc_book values(?,?,?)";
		super.executeUpdate(sql, book, new String[] {"bid","bname","price"});
	}
	
	public void delete(Book book) throws Exception {
		String sql  = "delete from t_mvc_book where bid = ?";
		super.executeUpdate(sql, book, new String[] {"bid"});
	}
	
	public void edit(Book book) throws Exception {
		String sql  = "update t_mvc_book set bname = ?,price = ? where bid = ?";
		super.executeUpdate(sql, book, new String[] {"bname","price","bid"});
	}
	
	public List<Book> list(Book book,PageBean pageBean) throws Exception {
		String sql  = "select * from t_mvc_book where 1=1 ";
		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);
	}
	
	public static void main(String[] args) throws Exception {
		Book book = new Book();
		book.setBid(2);
//		book.setBname("23225");
//		book.setPrice(23225f);
		BookDao bookDao = new BookDao();
//		bookDao.add(book);
//		bookDao.edit(book);
		bookDao.delete(book);
	}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>	
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>	
<!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
	href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
	rel="stylesheet">
<script
	src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<title>书籍列表</title>
<style type="text/css">
.page-item input {
	padding: 0;
	width: 40px;
	height: 100%;
	text-align: center;
	margin: 0 6px;
}

.page-item input, .page-item b {
	line-height: 38px;
	float: left;
	font-weight: 400;
}

.page-item.go-input {
	margin: 0 10px;
}
</style>
</head>
<body>
	<form class="form-inline"
		action="${pageContext.request.contextPath }/book.action?methodName=list" method="post">
		<div class="form-group mb-2">
			<input type="text" class="form-control-plaintext" name="bname"
				placeholder="请输入书籍名称">
<!-- 			<input name="rows" value="20" type="hidden"> -->
<!-- 不想分页 -->
				<input name="pagination" value="false" type="hidden">
		</div>
		<button type="submit" class="btn btn-primary mb-2">查询</button>
		<a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/book.action?methodName=toEdit">新增</a>
	</form>

	<table class="table table-striped">
		<thead>
			<tr>
				<th scope="col">书籍ID</th>
				<th scope="col">书籍名</th>
				<th scope="col">价格</th>
				<th scope="col">操作</th>
			</tr>
		</thead>
		<tbody>
			<c:forEach  var="b" items="${books }">
			<tr>
				<td>${b.bid }</td>
				<td>${b.bname }</td>
				<td>${b.price }</td>
				<td>
					<a href="${pageContext.request.contextPath }/book.action?methodName=toEdit&bid=${b.bid}">修改</a>
					<a href="${pageContext.request.contextPath }/book.action?methodName=delete&bid=${b.bid}">删除</a>
				</td>
			</tr>
			</c:forEach>
		</tbody>
	</table>
	<!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
	<z:page pageBean="${pageBean }"></z:page>

</body>
</html>

3.运行结果

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值