1.创建如下mysql脚本
1 drop table if exists book_info; 2 3 create table if not exists book_info( 4 book_id int(10) primary key auto_increment, 5 book_name varchar(50) not null, 6 book_author varchar(50) not null, 7 book_publish varchar(50) not null, 8 book_page int(10) not null, 9 book_price double(10,2) not null, 10 creation_time date not null 11 ); 12 13 insert into book_info 14 (book_name,book_author,book_publish,book_page,book_price,creation_time) 15 values 16 ('Java与模式','闫磊','电子工业出版社',1100,97.00,'2017-01-01'), 17 ('Java核心','(美)Cay S.Horstmann','机械工业出版社',678,333.00,'2017-01-02'), 18 ('Java编程思想','(美)Bruce Exkel','机械工业出版社',590,75.00,'2017-01-03'), 19 ('TCP/IP详解','(美)W.Ricahr Steves','机械工业出版社',205,90.20,'2017-01-04'), 20 ('什么是数学','R.阿朗','复旦大学出版社',521,42.00,'2017-01-05') 21 ; 22 23 select * from book_info;
2.创建项目Spring_Mybatis_Exam9
3.导入jar文件,注意:mysql是jar文件版本:mysql-connector-java-5.1.7-bin.jar或更高版本
4.在src下的com.pojo包下创建BookInfo.java
1 package com.pojo; 2 import java.io.Serializable; 3 public class BookInfo implements Serializable{ 4 private static final long serialVersionUID = 1L; 5 private Integer book_id ; 6 private Integer book_page ; 7 private Double book_price ; 8 private String book_name ; 9 private String book_author ; 10 private String book_publish ; 11 private String creation_time; 12 13 public BookInfo() { 14 } 15 16 public BookInfo(Integer bookPage, Double bookPrice, String bookName, 17 String bookAuthor, String bookPublish, String creationTime) { 18 book_page = bookPage; 19 book_price = bookPrice; 20 book_name = bookName; 21 book_author = bookAuthor; 22 book_publish = bookPublish; 23 creation_time = creationTime; 24 } 25 26 public BookInfo(Integer bookId, Integer bookPage, Double bookPrice, 27 String bookName, String bookAuthor, String bookPublish, 28 String creationTime) { 29 book_id = bookId; 30 book_page = bookPage; 31 book_price = bookPrice; 32 book_name = bookName; 33 book_author = bookAuthor; 34 book_publish = bookPublish; 35 creation_time = creationTime; 36 } 37 public Integer getBook_id() { 38 return book_id; 39 } 40 public void setBook_id(Integer bookId) { 41 book_id = bookId; 42 } 43 public Integer getBook_page() { 44 return book_page; 45 } 46 public void setBook_page(Integer bookPage) { 47 book_page = bookPage; 48 } 49 public Double getBook_price() { 50 return book_price; 51 } 52 public void setBook_price(Double bookPrice) { 53 book_price = bookPrice; 54 } 55 public String getBook_name() { 56 return book_name; 57 } 58 public void setBook_name(String bookName) { 59 book_name = bookName; 60 } 61 public String getBook_author() { 62 return book_author; 63 } 64 public void setBook_author(String bookAuthor) { 65 book_author = bookAuthor; 66 } 67 public String getBook_publish() { 68 return book_publish; 69 } 70 public void setBook_publish(String bookPublish) { 71 book_publish = bookPublish; 72 } 73 public String getCreation_time() { 74 return creation_time; 75 } 76 public void setCreation_time(String creationTime) { 77 creation_time = creationTime; 78 } 79 @Override 80 public String toString() { 81 return "BookInfo [book_author=" + book_author + ", book_id=" + book_id 82 + ", book_name=" + book_name + ", book_page=" + book_page 83 + ", book_price=" + book_price + ", book_publish=" 84 + book_publish + ", creation_time=" + creation_time + "]"; 85 } 86 }
5.在src下的com.page包下创建PageUtil.java
1 package com.page; 2 3 public class PageUtil { 4 private Integer pageno; 5 private Integer pagesize; 6 private Integer totalpage; 7 private Integer totalcount; 8 private Integer startrow; 9 10 public PageUtil() { 11 } 12 13 public PageUtil(Integer pageno, Integer pagesize, Integer totalcount) { 14 this.pageno = pageno; 15 this.pagesize = pagesize; 16 this.totalcount = totalcount; 17 this.setTotalpage(totalcount,pagesize); 18 this.setStartrow(pageno,pagesize); 19 } 20 21 public void setStartrow(Integer pageno, Integer pagesize) { 22 this.startrow=(pageno-1)*pagesize; 23 } 24 25 public void setTotalpage(Integer totalcount, Integer pagesize) { 26 this.totalpage=totalcount%pagesize==0?totalcount/pagesize:totalcount/pagesize+1; 27 28 } 29 30 public Integer getPageno() { 31 return pageno; 32 } 33 34 35 public void setPageno(Integer pageno) { 36 this.pageno = pageno; 37 } 38 39 40 public Integer getPagesize() { 41 return pagesize; 42 } 43 44 45 public void setPagesize(Integer pagesize) { 46 this.pagesize = pagesize; 47 } 48 49 50 public Integer getTotalpage() { 51 return totalpage; 52 } 53 54 55 56 57 58 public Integer getTotalcount() { 59 return totalcount; 60 } 61 62 63 public void setTotalcount(Integer totalcount) { 64 this.totalcount = totalcount; 65 } 66 67 68 public Integer getStartrow() { 69 return startrow; 70 } 71 72 }
6.在src下的com.mapper包下创建BookInfoMapper.java
1 package com.mapper; 2 import java.util.List; 3 import com.page.PageUtil; 4 import com.pojo.BookInfo; 5 public interface BookInfoMapper { 6 //分页查询 7 List<BookInfo> findPage(PageUtil pageutil); 8 //查询总条数 9 Integer getTotalCout(); 10 //根据主键查询对象 11 BookInfo findByPrimaryKey(Integer key); 12 //添加对象 13 Integer insertBookInfo(BookInfo bookInfo); 14 //根据主键修改对象 15 Integer updatePrimaryKey(BookInfo bookInfo); 16 //根据主键删除 17 Integer deletePrimaryKey(Integer key); 18 }
7.在src下的com.mapper包下创建BookInfoMapper.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" > 3 <mapper namespace="com.mapper.BookInfoMapper"> 4 <!-- 分页查询 --> 5 <select id="findPage" parameterType="PageUtil" resultType="BookInfo"> 6 select * from book_info limit #{startrow},#{pagesize} 7 </select> 8 <!-- 获取总条数 --> 9 <select id="getTotalCout" resultType="Integer"> 10 select count(*) from book_info 11 </select> 12 <!-- 查询单条 --> 13 <select id="findByPrimaryKey" parameterType="Integer" resultType="BookInfo"> 14 select * from book_info where book_id=#{book_id} 15 </select> 16 <!-- 添加 --> 17 <insert id="insertBookInfo" parameterType="BookInfo"> 18 insert into 19 book_info(book_name,book_author,book_publish,book_page,book_price,creation_time) 20 values(#{book_name},#{book_author},#{book_publish},#{book_page},#{book_price},#{creation_time}) 21 </insert> 22 <!-- 修改 --> 23 <update id="updatePrimaryKey" parameterType="BookInfo"> 24 update book_info 25 set 26 book_name=#{book_name}, 27 book_author=#{book_author}, 28 book_publish=#{book_publish}, 29 book_page=#{book_page}, 30 book_price=#{book_price}, 31 creation_time=#{creation_time} 32 where 33 book_id=#{id} 34 </update> 35 <!-- 删除 --> 36 <delete id="deletePrimaryKey" parameterType="Integer"> 37 delete from book_info where book_id=#{book_id} 38 </delete> 39 </mapper>
8.在src下创建log4j.properties
1 log4j.rootLogger=DEBUG, Console 2 3 #Console 4 log4j.appender.Console=org.apache.log4j.ConsoleAppender 5 log4j.appender.Console.layout=org.apache.log4j.PatternLayout 6 log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n 7 8 log4j.logger.org.apache=INFO 9 log4j.logger.java.sql.ResultSet=INFO 10 log4j.logger.java.sql.Connection=DEBUG 11 log4j.logger.java.sql.Statement=DEBUG 12 log4j.logger.java.sql.PreparedStatement=DEBUG
9.在src下创建mybaits-config.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd" > 3 <configuration> 4 <!-- 别名配置 --> 5 <typeAliases> 6 <typeAlias type="com.page.PageUtil" alias="PageUtil"/> 7 <typeAlias type="com.pojo.BookInfo" alias="BookInfo"/> 8 </typeAliases> 9 10 <!-- 和spring结合时,数据源配置在spring --> 11 12 <!-- 注册映射xml --> 13 <mappers> 14 <mapper resource="com/mapper/BookInfoMapper.xml"/> 15 </mappers> 16 </configuration>
10.在src下的com.mapper.impl包下创建BookInfoMapperImpl.java
1 package com.mapper.impl; 2 3 import java.util.List; 4 5 import org.apache.ibatis.session.SqlSessionManager; 6 import org.mybatis.spring.SqlSessionTemplate; 7 8 import com.mapper.BookInfoMapper; 9 import com.page.PageUtil; 10 import com.pojo.BookInfo; 11 12 public class BookInfoMapperImpl implements BookInfoMapper { 13 //定义sqlsession模板对象的 14 private SqlSessionTemplate sqlSessionTemplate; 15 //提供sqlsqlsession模板对象的getter和setter 16 public SqlSessionTemplate getSqlSessionTemplate() { 17 return sqlSessionTemplate; 18 } 19 public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { 20 this.sqlSessionTemplate = sqlSessionTemplate; 21 } 22 23 //------------------------------ 24 public Integer deletePrimaryKey(Integer key) { 25 BookInfoMapper mapper=sqlSessionTemplate.getMapper(BookInfoMapper.class); 26 return mapper.deletePrimaryKey(key); 27 } 28 29 public BookInfo findByPrimaryKey(Integer key) { 30 BookInfoMapper mapper=sqlSessionTemplate.getMapper(BookInfoMapper.class); 31 return mapper.findByPrimaryKey(key); 32 } 33 34 public List<BookInfo> findPage(PageUtil pageutil) { 35 BookInfoMapper mapper=sqlSessionTemplate.getMapper(BookInfoMapper.class); 36 return mapper.findPage(pageutil); 37 } 38 39 public Integer getTotalCout() { 40 BookInfoMapper mapper=sqlSessionTemplate.getMapper(BookInfoMapper.class); 41 return mapper.getTotalCout(); 42 } 43 44 public Integer insertBookInfo(BookInfo bookInfo) { 45 BookInfoMapper mapper=sqlSessionTemplate.getMapper(BookInfoMapper.class); 46 return mapper.insertBookInfo(bookInfo); 47 } 48 49 public Integer updatePrimaryKey(BookInfo bookInfo) { 50 BookInfoMapper mapper=sqlSessionTemplate.getMapper(BookInfoMapper.class); 51 return mapper.updatePrimaryKey(bookInfo); 52 } 53 54 }
11.在src下的com.service包下创建BookInfoService.java
1 package com.service; 2 import java.util.List; 3 import com.page.PageUtil; 4 import com.pojo.BookInfo; 5 public interface BookInfoService { 6 //分页查询 7 List<BookInfo> queryAll(PageUtil pageutil); 8 //查询总条数 9 Integer getTotalCout(); 10 //根据主键查询对象 11 BookInfo findBookInfo(Integer key); 12 //添加对象 13 Integer saveBookInfo(BookInfo bookInfo); 14 //根据主键修改对象 15 Integer editBookInfo(BookInfo bookInfo); 16 //根据主键删除 17 Integer deleteBookInfo(Integer key); 18 }
12.在src下的com.service.impl包下创建BookInfoServiceImpl.java
1 package com.service.impl; 2 3 import java.util.List; 4 5 import com.mapper.BookInfoMapper; 6 import com.page.PageUtil; 7 import com.pojo.BookInfo; 8 import com.service.BookInfoService; 9 10 public class BookInfoServiceImpl implements BookInfoService { 11 //定义数据访问层对象,值由spring通过setter注入 12 private BookInfoMapper mapper; 13 14 public BookInfoMapper getMapper() { 15 return mapper; 16 } 17 18 public void setMapper(BookInfoMapper mapper) { 19 this.mapper = mapper; 20 } 21 //---------------------------- 22 public Integer deleteBookInfo(Integer key) { 23 return mapper.deletePrimaryKey(key); 24 } 25 26 public Integer editBookInfo(BookInfo bookInfo) { 27 return mapper.updatePrimaryKey(bookInfo); 28 } 29 30 public BookInfo findBookInfo(Integer key) { 31 return mapper.findByPrimaryKey(key); 32 } 33 34 public Integer getTotalCout() { 35 return mapper.getTotalCout(); 36 } 37 public List<BookInfo> queryAll(PageUtil pageutil) { 38 return mapper.findPage(pageutil); 39 } 40 41 public Integer saveBookInfo(BookInfo bookInfo) { 42 // TODO Auto-generated method stub 43 return null; 44 } 45 46 }
13.在src下的com.servlet包下创建BookInfoServlet.java
1 package com.servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.List; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import org.springframework.context.ApplicationContext; 13 import org.springframework.context.support.ClassPathXmlApplicationContext; 14 15 import com.page.PageUtil; 16 import com.pojo.BookInfo; 17 import com.service.BookInfoService; 18 import com.service.impl.BookInfoServiceImpl; 19 20 public class BookInfoServlet extends HttpServlet { 21 22 public void doGet(HttpServletRequest request, HttpServletResponse response) 23 throws ServletException, IOException { 24 this.doPost(request, response); 25 } 26 27 public void doPost(HttpServletRequest request, HttpServletResponse response) 28 throws ServletException, IOException { 29 //1.乱码处理 30 request.setCharacterEncoding("UTF-8"); 31 response.setCharacterEncoding("UTF-8"); 32 response.setContentType("text/html;charset=UTF-8"); 33 34 //2.接收请求参数 35 String flag=request.getParameter("flag"); 36 37 //3.加载spring的xml文件 38 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); 39 40 //4.由于原来sevelt调用service 41 //在此处调用springxml中的service的bean节点,获取service对象 42 BookInfoServiceImpl serviceImpl=(BookInfoServiceImpl) ac.getBean("bookInfoServiceImpl"); 43 44 //5.业务处理 45 if(flag==null){ //5.1 分页查询 46 //获取第二次页面分页超链接请求“当前页的”参数的值 47 String strpageno=request.getParameter("pageno"); 48 //定义第一次请求当前页的的默认值 49 Integer pageno=1; 50 //判断是否是第二次请求。由于页面上的参数全部是string类型,所以转换 51 if(strpageno!=null){ 52 pageno=Integer.valueOf(strpageno); 53 } 54 //定义页面大小 55 Integer pagesize=3; 56 //查询总条数 57 Integer totalcount=serviceImpl.getTotalCout(); 58 //计算总页数 59 Integer totalpage=totalcount%pagesize==0?totalcount/pagesize:totalcount/pagesize+1; 60 //封装分页参数给工具类 61 PageUtil pageutil=new PageUtil(pageno, pagesize, totalcount); 62 //执行分页查询操作 63 List<BookInfo> list=serviceImpl.queryAll(pageutil); 64 if(list!=null){ 65 System.out.println("find success"); 66 request.setAttribute("list", list); 67 request.getRequestDispatcher("index.jsp").forward(request, response); 68 }else{ 69 System.out.println("find fail"); 70 } 71 }else if(flag=="add"){ 72 73 } 74 75 76 } 77 78 }
14.在WebRoot下的WEB-INF下编辑web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7 8 <servlet> 9 <servlet-name>BookInfoServlet</servlet-name> 10 <servlet-class>com.servlet.BookInfoServlet</servlet-class> 11 </servlet> 12 13 <servlet-mapping> 14 <servlet-name>BookInfoServlet</servlet-name> 15 <url-pattern>/BookInfoServlet</url-pattern> 16 </servlet-mapping> 17 <welcome-file-list> 18 <welcome-file>BookInfoServlet</welcome-file> 19 </welcome-file-list> 20 </web-app>
15.在src下创建applicationContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:aop="http://www.springframework.org/schema/aop" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:mvc="http://www.springframework.org/schema/mvc" 7 xmlns:xsd="http://www.w3.org/2001/XMLSchema" 8 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 9 xsi:schemaLocation="http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop.xsd 13 http://www.springframework.org/schema/context 14 http://www.springframework.org/schema/context/spring-context.xsd 15 http://www.springframework.org/schema/tx 16 http://www.springframework.org/schema/tx/spring-tx.xsd 17 http://www.springframework.org/schema/mvc 18 http://www.springframework.org/schema/mvc/spring-mvc.xsd 19 "> 20 <!-- ☆ 1.数据源配置:驱动管理数据源 --> 21 <!-- 22 类似java的:DriverManagerDataSource dataSource=new DriverManagerDataSource(); 23 --> 24 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 25 <!--类似java的:dataSource.setDriverClassName("com.mysql.jdbc.Driver"); --> 26 <property name="driverClassName" value="com.mysql.jdbc.Driver"/> 27 28 <!--类似java的:dataSource.setUrl("jdbc:mysql://localhost:3306/holly"); --> 29 <property name="url" value="jdbc:mysql://localhost:3306/holly"/> 30 31 <!--类似java的:dataSource.setUsername("root"); --> 32 <property name="username" value="root"/> 33 34 <!--类似java的:dataSource.setPassword("ok"); --> 35 <property name="password" value="ok"/> 36 </bean> 37 38 <!-- ☆ 2.sqlsessionfactoryBean --> 39 <!--类似java的:SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean(); --> 40 <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> 41 <!-- 2.1 引入数据源 --> 42 <!--类似java的:sqlSessionFactoryBean.setDataSource(dataSource); --> 43 <property name="dataSource" ref="dataSource"/> 44 45 <!-- 2.2 加载mybatis主配置文件 --> 46 <!--类似java的:sqlSessionFactoryBean.setConfigLocation("classpath:mybaits-config.xml"); --> 47 <property name="configLocation"> 48 <value>classpath:mybaits-config.xml</value> 49 </property> 50 </bean> 51 52 <!-- 3.sqlsessionTemplate --> 53 <!--类似java的:SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(sqlSessionFactoryBean); --> 54 <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> 55 <!-- 通过构造赋值 --> 56 <constructor-arg ref="sqlSessionFactoryBean"/> 57 </bean> 58 59 <!-- 4.数据访问层的注入:new对象完成赋值 --> 60 <!--BookInfoMapperImpl bookInfoMapper=new BookInfoMapperImpl(); --> 61 <bean id="bookInfoMapperImpl" class="com.mapper.impl.BookInfoMapperImpl"> 62 <!--bookInfoMapper.setSqlSessionTemplate(sqlSessionTemplate); --> 63 <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/> 64 </bean> 65 66 <!-- 5.业务层的的注入:new对象完成赋值 --> 67 <!--BookInfoServiceImpl bookInfoServiceImpl=new BookInfoServiceImpl(); --> 68 <bean id="bookInfoServiceImpl" class="com.service.impl.BookInfoServiceImpl"> 69 <!--bookInfoServiceImpl.setBookInfoMapper(bookInfoMapperImpl); --> 70 <property name="mapper" ref="bookInfoMapperImpl"/> 71 </bean> 72 73 74 75 </beans>
16.在WebRoot下编辑index.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 6 %> 7 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 9 <html> 10 <head> 11 <base href="<%=basePath%>"> 12 13 <title>My JSP 'index.jsp' starting page</title> 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 </head> 23 24 <body> 25 <center> 26 <fieldset> 27 <legend>图书信息</legend> 28 <a href="add.jsp">保存图书信息</a> 29 <table border="1"> 30 <tr> 31 <td>编号</td> 32 <td>书名</td> 33 <td>作者</td> 34 <td>出版社</td> 35 <td>页数</td> 36 <td>价格</td> 37 <td>出版时间</td> 38 <td>操作</td> 39 </tr> 40 <c:forEach var="i" items="${list}"> 41 <tr> 42 <td>${i.book_id}</td> 43 <td>${i.book_name}</td> 44 <td>${i.book_author}</td> 45 <td>${i.book_publish}</td> 46 <td>${i.book_page}</td> 47 <td>${i.book_price}</td> 48 <td>${i.creation_time}</td> 49 <td> 50 <a href="BookInfoServlet?flag=findbyid&id=${i.book_id}">修改</a> 51 | 52 <a href="BookInfoServlet?flag=delete&id=${i.book_id}">删除</a> 53 </td> 54 </tr> 55 </c:forEach> 56 </table> 57 </fieldset> 58 </center> 59 </body> 60 </html>
17.运行
本文原创,如有问题,请联系holly老师:转载请备注出处!