1. 程式人生 > 程式設計 >spring+mybatis實現圖書管理系統

spring+mybatis實現圖書管理系統

一、流程
jsp頁面發起請求-->控制器-->控制器通過一個service物件呼叫service方法-->service中通過xxxMapper物件呼叫dao中的方法-->查詢資料庫

二、圖書管理系統
1、目錄結構


2、Book實體類
package com.entity;

import java.io.Serializable;
import java.util.Map;
import org.apache.ibatis.type.Alias;

public class Book implements Serializable{


private static final long serialVersionUID = 1L;

private Integer id;
private String name;
private String author;
private String bookconcern;
private String date;
private String synopsis;
private String pic;

public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic == null ? null : pic.trim();
}

public Book() {
super();
}
public Book(Integer id,String name,String author,String bookconcern,String date,String synopsis,String pic) {
super();
this.id = id;
this.name = name;
this.author = author;
this.bookconcern = bookconcern;
this.date =date;
this.synopsis = synopsis;
this.pic = pic == null ? null : pic.trim();
}


public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getBookconcern() {
return bookconcern;
}
public void setBookconcern(String bookconcern) {
this.bookconcern = bookconcern;
}
public String getDate() {
return date;
}


public void setDate(String date) {
this.date = date;
}


public String getSynopsis() {
return synopsis;
}


public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String toString() {
return "Book [id=" + id + ",name=" + name + ",author="
+ author + ",bookconcern=" + bookconcern + ",date=" + date + ",synopsis=" + synopsis +",pic=" + pic+"]";
}

}


3、BookMapper增刪改查介面
package com.dao;

import java.util.List;
import org.springframework.web.multipart.MultipartFile;
import com.entity.Book;

public interface BookMapper {

public Book getBookById(Integer id);
public List<Book> getBooks();
public void insertBook(Book book);
public void deleteBookById(Integer id);
public void updateBook(Book book);
public Book findById(Integer id);

}

4、BookMapper.xml實現增刪改查操作
<?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.dao.BookMapper">
<select id="getBooks" resultType="com.entity.Book">
select * from book
</select>

<insert id="insertBook" >
insert into book
(name,author,bookconcern,date,synopsis,pic)values(#{name},#{author},#{bookconcern},#{date},#{synopsis},#{pic});
</insert>

<delete id="deleteBookById" >
delete from book
where id=#{id}
</delete>

<update id="updateBook">
update book set
name=#{name},author=#{author},bookconcern=#{bookconcern},date=#{date},synopsis=#{synopsis},pic=#{pic} where
id=#{id}
</update>

<select id="findById" parameterType="int" resultType="com.entity.Book">
select *
from book where id=#{id};
</select>

</mapper>

5、控制類
package com.controller;


import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import com.entity.Book;
import com.service.BookService;


@Controller
public class BookController {

@Autowired
BookService bookService;

@RequestMapping("/getbooks")
public String books(Map<String,Object> map){
List<Book> books = bookService.getBooks();
map.put("allBooks",books);
return "allbooks";
}

@RequestMapping(value="/insert",produces="text/html;charset=UTF-8")
public String insert(){
return "insert";
}

@RequestMapping(value="/insertBook")
public String insertBook(Book book,MultipartFile book_pic) throws IllegalStateException,IOException{

String originalFilename = book_pic.getOriginalFilename();
if(book_pic!=null && originalFilename!=null && originalFilename.length()>0){
String pic_path = "E:\\spring_mybatis\\picture\\";
String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
File newFile = new File(pic_path+newFileName);
book_pic.transferTo(newFile);
book.setPic(newFileName);
}
bookService.insertBook(book);
return "redirect:getbooks";
}

@RequestMapping(value="/deleteBookById")
public String deleteBookById(Integer id){
bookService.deleteBookById(id);
return "redirect:getbooks";
}

@RequestMapping(value="/findById")
public String findById(Model model,Integer id){
Book book=bookService.findById(id);
model.addAttribute("book",book);
return "update";
}

@RequestMapping(value="/updateBook")
public String updateBook(Book book,IOException{

String originalFilename = book_pic.getOriginalFilename();
if(book_pic!=null && originalFilename!=null && originalFilename.length()>0){
String pic_path = "E:\\spring_mybatis\\picture\\";
String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
File newFile = new File(pic_path+newFileName);
book_pic.transferTo(newFile);
book.setPic(newFileName);
}
bookService.updateBook(book);
return "redirect:getbooks";

}

}


6、BookService操作
package com.service;

import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.dao.BookMapper;
import com.entity.Book;

@Service //標識這是一個業務類
public class BookService {

@Autowired //用@Autowired將BookMapper的介面物件注入到spring中
private BookMapper bookMapper;
@Autowired
private SqlSession sqlSession;

public List<Book> getBooks(){
return bookMapper.getBooks();
}

public void insertBook(Book book) {
bookMapper.insertBook(book);
}

public void deleteBookById(Integer id) {
bookMapper.deleteBookById(id);
}

public void updateBook(Book book) {
bookMapper.updateBook(book);
}

public Book findById(Integer id) {
return bookMapper.findById(id);
}
}

7、mybatis配置檔案mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="jdbcTypeForNull" value="NULL"/>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>

<databaseIdProvider type="DB_VENDOR">
<property name="MySQL" value="mysql"/>
<property name="SQL Server" value="sqlserver"/>
</databaseIdProvider>

</configuration>

8、spring配置檔案applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<context:component-scan base-package="com">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>

<!-- 引入資料庫的配置檔案 -->
<context:property-placeholder location="classpath:dbconfig.properties" />

<!-- spring用來控制業務邏輯 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>

<!-- spring事務管理 -->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 基於註解的事務 -->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>

<!--創建出SqlSessionFactory物件 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>

<!-- configLocation指定全域性配置檔案的位置 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>

<!--mapperLocations: 指定mapper檔案的位置-->
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"></property>
</bean>

<!--配置一個可以進行批量執行的sqlSession -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean"></constructor-arg>
<constructor-arg name="executorType" value="BATCH"></constructor-arg>
</bean>

<!-- base-package:指定mapper介面的包名 -->
<mybatis-spring:scan base-package="com.dao"/>

</beans>

9、連線資料庫資訊dbconfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/login?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456

10、web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>spring_mybatis</display-name>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

11、spring mvc配置檔案spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<!-- 只掃描控制器 -->
<context:component-scan base-package="com" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!-- 檢視解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

<mvc:annotation-driven></mvc:annotation-driven>
<mvc:default-servlet-handler/>
</beans>

12、jsp頁面
(1)index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>首頁</title>
<style type="text/css">
#top{
border:1px solid gainsboro;
width:100%;
height:100px;
}
#left{
border:1px solid gainsboro;
float:left;
width:10%;
height:400px;
}
#left ul{
width:980px;
margin:0px auto;
height:38px;
padding:0;
}
#left ul li a{
width:80px;
height:28px;
line-height:28px;
background:gray;
color:#FFF;
margin:5px 10px;
font-size:16px;
display:block;
text-align:center;
text-decoration:none;
}
#left ul li a:hover{
width:78px;
height:26px;
line-height:28px;
color:gray;
background:#FFF;
}
#right{
border:1px solid gainsboro;
width:89%;
height:400px;
float:right;
}
</style>
</head>
<body>


<div id="top">
<img src="img/title.jpg" />
</div>
<div id="left">
<ul>
<li><a href="getbooks" rel="external nofollow" >所有圖書</a></li>
<li><a href="insert" rel="external nofollow" >新增圖書</a></li>
</ul>
</div>
<div id="right">
<img src="img/3.jpg" width=100% height=100%>
</div>
</body>
</html>

(2)allbooks.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>所有圖書</title>

</head>
<body>
<table align="center" border="5" width=70% height=60%>
<tr>
<td colspan="7"><h1>所有圖書</h1></td>
</tr>
<tr>
<td align="center" >編號</td>
<td align="center">書名</td>
<td align="center" width=10% >作者</td>
<td align="center">出版社</td>
<td align="center" width=15% >出版時間</td>
<td align="center">簡介</td>
<td align="center">圖書圖片</td>
<td align="center" width=12%>操作</td>
</tr>

<c:forEach items="${allBooks }" var="book">
<tr>
<td>${book.id }</td>
<td>${book.name }</td>
<td>${book.author }</td>
<td>${book.bookconcern }</td>
<td>${book.date }</td>
<td>${book.synopsis }</td>
<td>
<c:if test="${book.pic !=null}">
<img src="/pic/${book.pic}" width=100 height=100/>
<br/>
</c:if>
</td>
<td align="center"><a href="deleteBookById?id=${book.id }" rel="external nofollow" >刪除</a>|<a href="findById?id=${book.id} " rel="external nofollow" >修改</a></td>
</tr>

</c:forEach>
<tr><td border="0"><input type="button" value="返回首頁" οnclick="javascript:window.location.href ='index.jsp';"/></td></tr>
</table>
</body>
</html>
(3)insert.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>新增圖書</title>
</head>
<body>
<form action="insertBook" method="post" enctype="multipart/form-data" enctype="multipart/form-data">
<table border="5" align="center" width=70% height=60%>
<tr>
<td colspan="2"><h1>新增圖書</h1></td>
</tr>
<tr>
<td>書籍名稱:</td>
<td><input type="text" name="name" size=85/></td>
</tr>
<tr>
<td>書籍作者:</td>
<td><input type="text" name="author" size=85/></td>
</tr>
<tr>
<td>出版社:</td>
<td><input type="text" name="bookconcern" size=85/></td>
</tr>
<tr>
<td>出版時間:</td>
<td><input type="text" name="date" size=85/></td>
</tr>
<tr>
<td>簡介:</td>
<td><input type="text" name="synopsis" size=85/></td>
</tr>

<tr>
<td>圖書圖片</td>
<td>
<input type="file" name="book_pic"/>
</td>
</tr>

<tr>
<td colspan="2">
<input type="submit" value="提交"/>
<input type="reset" value="清空"/>
<input type="button" value="返回首頁" οnclick="javascript:window.location.href ='index.jsp';"/>
</td>
</tr>
</table>
</form>
</body>
</html>
(4)update.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改圖書資訊</title>
</head>

<body>
<form action="updateBook" method="post" enctype="multipart/form-data" >
<table border="5" align="center" width=70% height=60%>
<tr>
<td colspan="2"><h1>修改圖書資訊</h1></td>
</tr>
<tr>
<td>編號:</td>
<td><input type="text" name="id" value="${book.id}" readonly="readonly" size=85/></td>
</tr>

<tr>
<td>書名:</td>
<td><input type="text" name="name" value="${book.name}" size=85/></td>
</tr>
<tr>
<td>作者:</td>
<td><input type="text" name="author" value="${book.author}" size=85/></td>
</tr>
<tr>
<td>出版社:</td>
<td><input type="text" name="bookconcern" value="${book.bookconcern}" size=85/></td>
</tr>
<tr>
<td>出版時間:</td>
<td><input type="text" name="date" value="${book.date}" size=85/></td>
</tr>
<tr>
<td>簡介:</td>
<td><input type="text" name="synopsis" value="${book.synopsis}" size=85/></td>
</tr>
<tr>
<td>圖書圖片</td>
<td>
<c:if test="${book.pic !=null}">
<img src="/pic/${book.pic}" width=100 height=100/>
<br/>
</c:if>
<input type="file" name="book_pic"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交"/>
<input type="button" value="返回首頁" οnclick="javascript:window.location.href ='index.jsp';"/>
</td>
</tr>
</table>
</form>
</body>
</html>

13、所需的jar包