org.projectlombok
lombok
1.18.12
junit
junit
4.12
mysql
mysql-connector-java
5.1.47
com.mchange
c3p0
0.9.5.2
javax.servlet
servlet-api
2.5
javax.servlet.jsp
jsp-api
2.2
javax.servlet
jstl
1.2
taglibs
standard
1.1.2
org.mybatis
mybatis
3.5.2
org.mybatis
mybatis-spring
2.0.2
org.springframework
spring-webmvc
5.1.9.RELEASE
org.springframework
spring-jdbc
5.1.9.RELEASE
src/main/java
**/*.properties
**/*.xml
false
src/main/resources
**/*.properties
**/*.xml
false
`ssmbuild``books`CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
建立pojo包,然后建立对应的实体类Books
package com.zhou.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private String bookCounts;
private String detail;
}
mybatis-config.xml
<configuration>
<typeAliases>
<package name="com.zhou.pojo"/>
typeAliases>
<mappers>
<mapper resource="com/zhou/mapper/BookMapper.xml"/>
mappers>
configuration>
在此处注释掉的内容为后续mybatis测试数据库提供了一定的支持,后续由于有spring,则被spring接管,便被注释掉了!!
数据源文件:db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
# username=root
# password=123456
此处注释是由于测试时,总说用户和密码的问题,为防止名字和一些参数混淆,所以直接在后面采用固定的写法,所以注释掉
BookMapper
package com.zhou.mapper;
import com.zhou.pojo.Books;
import java.util.List;
public interface BookMapper {
//查询全部书
List<Books> getAllBooks();
//根据id 查询书
Books getBookByID(int id);
//增加书籍
int addBook(Books books);
//根据id删除书籍
int deleteBook(int id);
//修改书籍
int updateBook(Books books);
}
BookMapper.xml
<mapper namespace="com.zhou.mapper.BookMapper">
<select id="getAllBooks" resultType="Books">
select * from ssmbuild.books
select>
<select id="getBookByID" resultType="Books">
select * from ssmbuild.books where bookID=#{id}
select>
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books(bookName,bookCounts,detail)values (#{bookName},#{bookCounts},#{detail});
insert>
<delete id="deleteBook" parameterType="int">
delete from ssmbuild.books where bookID=#{bookID}
delete>
<update id="updateBook" parameterType="Books">
update ssmbuild.books
set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID=#{bookID}
update>
mapper>
mybatis整合完毕,进行相应的测试:
@org.junit.Test
public void Test1() throws IOException {
// InputStream is = BookMapper.class.getClassLoader().getResourceAsStream("db.properties");
String resource="mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sessionFactory.openSession();
BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
List allBooks = bookMapper.getAllBooks();
for (Books allBook : allBooks) {
System.out.println(allBook);
}
}
在实际业务中,service是业务层,可以调用mapper层,故编写service层的接口和实现类,方便spring的接管
BookService
package com.zhou.service;
import com.zhou.pojo.Books;
import java.util.List;
public interface BookService {
//查询全部书
List<Books> getAllBooks();
//根据id 查询书
Books getBookByID(int id);
//增加书籍
int addBook(Books books);
//根据id删除书籍
int deleteBook(int id);
//修改书籍
int updateBook(Books books);
}
BookServiceImpl
import java.util.List;
@Service
public class BookServiceImpl implements BookService {
@Autowired//自动将bean注入
private BookMapper bookMapper;
public List<Books> getAllBooks() {
List<Books> allBooks = bookMapper.getAllBooks();
return allBooks;
}
public Books getBookByID(int id) {
return bookMapper.getBookByID(id);
}
public int addBook(Books books) {
return bookMapper.addBook(books);
}
public int deleteBook(int id) {
return bookMapper.deleteBook(id);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
}
此处采用注解的方式,将mapper层的对应bean进行注入,简单高效!
在这里将写四个配置文件:
applicationContext.xml 引入其他三个
spring-mapper.xml
spring-mvc.xml
spring-service.xml
spring-mapper.xml:需要引入数据元的配置文件,定义数据库连接池,获得sqlSession,方便操作直接数据库
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="10000"/>
<property name="acquireRetryAttempts" value="2"/>
bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactory">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
<property name="basePackage" value="com.zhou.mapper"/>
bean>
beans>
spring-service.xml
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.zhou.service"/>
<bean class="com.zhou.service.BookServiceImpl">
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
bean>
beans>
在此处进行了事务的配置,以及将mapper层的bean进行了注册,并且开启了自动扫描service层的包。
spring-mvc.xml
<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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.zhou.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
<bean class="com.zhou.service.BookServiceImpl" id="bookService"/>
beans>
此处的整合可以详细参考springmvc的博客
博客地址
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-mapper.xml"/>
<import resource="spring-mvc.xml"/>
<import resource="spring-service.xml"/>
beans>
在这里必须将项目添加web的支持
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>DispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>DispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
filter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<session-config>
<session-timeout>15session-timeout>
session-config>
web-app>
注意此处关联的配置文件为:applicationContext.xml
编写controller层
Bookcontroller
package com.zhou.controller;
import com.zhou.pojo.Books;
import com.zhou.service.BookService;
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 java.util.List;
//调用业务层
@Controller
@RequestMapping("/book")
public class Bookcontroller {
@Autowired
private BookService bookService;
@RequestMapping("/allbook")
public String allbook(Model model) {
System.out.println("Bookcontroller进来了");
List<Books> list = bookService.getAllBooks();
model.addAttribute("list",list);
System.out.println(list);
return "allBooks";
}
// 新增书籍
@RequestMapping("/toaddBook")
public String toaddBook(){
return "addBook";
}
@RequestMapping("/addBookget")
public String addBook(Books book){
//注意是从前台获得增加的书籍,添加到后台
bookService.addBook(book);
System.out.println("增加的书:"+book);
return "redirect:/book/allbook";
}
//修改书籍 携带书的id进行跳转
@RequestMapping("/toupdateBook")
public String toupdate(int id,Model model){
//根据书的id进行查询
Books book = bookService.getBookByID(id);
System.out.println("修改的书籍为:"+book);
model.addAttribute("updatebook",book);
return "updateBook";
}
@RequestMapping("/updateBookget")
public String update(Books book){
bookService.updateBook(book);
Books book1 = bookService.getBookByID(book.getBookID());
// model.addAttribute("book1",book1);
System.out.println("修改好的书籍为:"+book1);
return "redirect:/book/allbook";
}
//删除书籍
@RequestMapping("/deleteBook")
public String delete(int id){
int i = bookService.deleteBook(id);
System.out.println("删除的书籍"+i);
return "redirect:/book/allbook";
}
}
此处是书籍增删改查全部执行程序,接下来分开详细进行介绍,注意开程序编写时,要多进行调试,确实程序没有问题,才接着往下写!!
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
书籍列表
点击进入列表
样式比较丑,可以后期进行修改!
全部书籍显示:
allBooks.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--上面的必须加,否则无法引入标签--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
全部书籍
此处由于要循环遍历,所以引入了标签库
新增书籍:
addBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
新增书籍
通过表单进行提交,由于id可以自增,所以不需要管!!
修改书籍
updateBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
修改书籍