创建一个存放书籍的数据库表:
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,'从进门到进牢');
新建一个maven项目,添加web支持,第一步先导jar包:junit、数据库、数据库连接池、servlet、mybatis、spring相关jar包和maven资源过滤支持:
<!--junit、数据库驱动、数据库连接池、servlet、mybatis、、spring-->
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<!--json依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.1</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
点击项目结构,点击Artifacts在WEB-INF下新建一个lib,将依赖导入进去,然后在src/main/java下创建四层同级的包:service层、controller层、pojo层、dao层,路径为com.cjh.service…在idea中连接数据库,现在先在resources资源下新建一个database.properties文件用于存放mysql的相关信息:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf8
user=root
password=123456
这里有两个注意点可能会报错:mysql8.0+的需要在url中添加时区设置&serverTimezone=UTC,还有user不能换成username不然也会报错
在resources资源下新建一个mybatis-config.xml文件用来设置mybatis的配置文件:
<?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>
<typeAliases>
<package name="com.cjh.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.cjh.dao.BookMapper"/>
</mappers>
</configuration>
接下来在pojo包下创建一个实体类用lombok注释:
package com.cjh.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
接下来在dao层创建一个BookMapper接口:
package com.cjh.dao;
import com.cjh.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.*;
public interface BookMapper {
//增加一本书
int addBook(Books book);
//删除一本书
int deleteBookById(@Param("bookId") int id);
//更改一本书
int updateBook(Books book);
//查询一本书
Books queryBookById(@Param("bookId")int id);
//查询所有的熟
List<Books> queryAllBook();
}
编写对应接口的Mapper.xml文件,需要导入Mybatis的包:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cjh.dao.BookMapper">
<insert id="addBook" parameterType="books">
insert into ssmbuild.books (bookName, bookCounts, detail)
values (#{bookName},#{bookCounts},#{detail});
</insert>
<delete id="deleteBookById" parameterType="int">
DELETE FROM ssmbuild.books WHERE bookID=#{bookId};
</delete>
<update id="updateBook" parameterType="books">
update ssmbuild.books set bookName = #{bookName},
bookName = #{bookName},
bookCounts = #{bookCounts},
detail = #{detail}
where bookID = #{bookID};
</update>
<select id="queryBookById" parameterType="int" resultType="books">
SELECT * FROM ssmbuild.books WHERE bookID=#{bookId};
</select>
<select id="queryAllBook" parameterType="books">
SELECT * FROM ssmbuild.books;
</select>
</mapper>
在service层创建一个BookService接口和实现类:
package com.cjh.service;
import com.cjh.pojo.Books;
import java.util.List;
public interface BookService {
//增加一本书
int addBook(Books book);
//删除一本书
int deleteBookById( int id);
//更改一本书
int updateBook(Books book);
//查询一本书
Books queryBookById(int id);
//查询所有的熟
List<Books> queryAllBook();
}
package com.cjh.service;
import com.cjh.dao.BookMapper;
import com.cjh.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService{
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Books book) {
return bookMapper.addBook(book);
}
@Override
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
@Override
public int updateBook(Books book) {
return bookMapper.updateBook(book);
}
@Override
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
@Override
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
到这里底层的需求已经编写完毕。
下面开始整合mybatis和spring,我们这里数据源使用c3p0连接池;
我们去编写Spring整合Mybatis的相关的配置文件;spring-dao.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"
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">
<!--1.关联数据库文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!--2.绑定源数据-->
<!--3.连接数据库-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--4.创建sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
<!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.cjh.dao"/>
</bean>
</beans>
配置spring-service.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:tx="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">
<!--1.扫描service相关的bean-->
<tx:component-scan base-package="com.cjh.service"/>
<!--2.将BookServiceImpl注入到spring容器中-->
<bean id="bookServiceImpl" class="com.cjh.service.BookServiceImpl">
<property name="bookMapper" value="bookMapper"/>
</bean>
<!--3.配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据库连接池-->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
这里可能出现bookMapper或者是dataSource爆红查看一下spring-dao下
中的路径是否正确
这个时候我们只剩下springmvc没有配置了
在web.xml中:
<?xml version="1.0" encoding="UTF-8"?>
<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_3_1.xsd"
version="3.1">
<!--DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--这里要注意是加载总的配置文件-->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--encodingFilter解决乱码问题-->
<filter>
<filter-name>encodingFilter</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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*
15
spring-mvc.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/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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置SpringMVC -->
<!-- 1.开启SpringMVC注解驱动 -->
<!-- 防止json乱码问题 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--静态资源默认servlet配置-->
<mvc:default-servlet-handler/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<!--扫描controller层相关的bean-->
<context:component-scan base-package="com.cjh.controller"/>
</beans>
applicationContext总配置文件下:
<?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:tx="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">
<import resource="classpath:spring-mvc.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-dao.xml"/>
</beans>
到这里我们就已经把所有的配置文件配置好了
在WEB-INF下新建一个jsp的文件夹,接下来我们开始写controller层,在controller层新建一个类
package com.cjh.controller;
import com.cjh.pojo.Books;
import com.cjh.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 list(Model model){
List<Books> list = bookService.queryAllBook();
model.addAttribute("list",list);
return "allBook";
}
}
index.jsp的测试代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
<h1>
<a href="${pageContext.request.contextPath}/book/allBook">点击进入列表页</a>
</h1>
</body>
</html>
和WEB-INF/jsp下的allBook.jsp的测试代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍列表</title>
</head>
<body>
<h3>书籍列表</h3>
</body>
</html>
配置tomcat以后开始运行
出现了错误500:java.lang.IllegalStateException: Cannot convert value of type ‘java.lang.String’ to required type ‘com.cjh.dao.BookMapper’ for property ‘bookMapper’: no matching editors or conversion strategy found
经排查发现是spring-service.xml中
中的value=“bookMapper”应该为ref=“bookMapper”
如果出现bookMapper出现爆红可能是idea中的bug
重新启动后出现500错误:org.apache.ibatis.executor.ExecutorException: A query was run and no Result Maps were found for the Mapped Statement ‘com.cjh.dao.BookMapper.queryAllBook’. It’s likely that neither a Result Type nor a Result Map was specified.经排查发现是dao层下的BookMapper.xml文件中
<select id="queryAllBook" parameterType="books">
SELECT * FROM ssmbuild.books;
</select>
parameterType="books"应该改为resultType=“books”
再次启动后能够正常跳转。