对t_mvc_book表的增删改查
导入jar包
BaseDao
package com.hmc.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; /** * 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; } }
Book(实体)
package com.hmc.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(); } }
BookDao
package com.hmc.dao; import java.util.List; import com.hmc.entity.Book; import com.hmc.util.BaseDao; import com.hmc.util.PageBean; import com.hmc.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.hmc.web; import java.util.List; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hmc.dao.BookDao; import com.hmc.entity.Book; import com.hmc.framework.ActionSupport; import com.hmc.framework.ModelDrivern; import com.hmc.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; } }
mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- config标签:可以包含0~N个action标签 --> <config> <!-- action标签:可以饱含0~N个forward标签 path:以/开头的字符串,并且值必须唯一 非空 type:字符串,非空 --> <action path="/Cal" type="com.hmc.web.AddCalAction"> <forward name="res" path="/res.jsp" redirect="false" /> </action> <action path="/book" type="com.hmc.web.BookAction"> <forward name="list" path="/book.jsp" redirect="false" /> <forward name="edit" path="/booklist.jsp" redirect="false" /> <forward name="tolist" path="/book.action?menthodName=list" /> </action> </config>
建立web层进行测试(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="z" 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> <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> <z:page bean="${pagebean }"></z:page> </body> </html>
模糊查询
删除上面编号为23的
新增书籍
修改十里桃花为百里桃花