Springmvc和mybatis整合
1. 整合思路
2. 准备环境
1) 框架版本
Spring3.1.1
Mybatis 3.1.0
2) 开发工具版本
Tomcat: apache-tomcat-8.0.30
Eclipse: OxygenRelease (4.7.0)
Jdk: 1.8.0_101
Mysql: mysql-5.7.17
3) 数据库文件
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `items`
-- ----------------------------
DROP TABLE IF EXISTS `items`;
CREATE TABLE `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`price` int(11) DEFAULT NULL,
`detail` varchar(500) DEFAULT NULL,
`pic` text,
`creattime` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of items
-- ----------------------------
INSERT INTO `items` VALUES ('1', 'apple1', '9000', '质量不错', 'ddd.jpg', '2017-08-24 20:49:21');
INSERT INTO `items` VALUES ('2', 'apple2', '7000', 'good', 'nice.png', '2017-08-15 20:50:38');
INSERT INTO `items` VALUES ('3', 'pro1', '8000', 'nice', 'fuck.jgp', '2017-08-07 20:51:16');
3. 整合dao
1) SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTDConfig 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 全局setting配置,需要时添加 -->
<!--<settings></settings> -->
<typeAliases>
<!-- 批量扫描别名 -->
<package name="cn.hr.ssm.po"/>
</typeAliases>
<!-- 配置mapper -->
</configuration>
2) applicationContext-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 加载db.properties文件中的内容, -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置连接源 dbcp commons-dbcp-1.4.jar-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="30"/>
<property name="maxIdle" value="5"/>
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 加载mybatis全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml"></property>
</bean>
<!-- mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.hr.ssm.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
3) 逆向工程生成po类和mapper
4) 手动定义商品查询mapper
a) ItemsMapperCustom.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="cn.hr.ssm.mapper.ItemsMapperCustom">
<!-- 定义sql片段 -->
<sql id="query_items_where">
<if test="itemsCustom!=null">
<if test="itemsCustom.name!=null anditemsCustom.name!=''">
WHERE name like'%{itemsCustom.name}%'
</if>
</if>
</sql>
<select id="findItemList"
parameterType="cn.hr.ssm.po.ItemsQueryVo"
resultType="cn.hr.ssm.po.ItemsCustom">
SELECT * FROM items
<where>
<include refid="query_items_where"></include>
</where>
</select>
</mapper>
b) ItemsMapperCustom.java
package cn.hr.ssm.mapper;
import java.util.List;
import cn.hr.ssm.po.ItemsCustom;
import cn.hr.ssm.po.ItemsQueryVo;
public interface ItemsMapperCustom {
public List<ItemsCustom> findItemList(ItemsQueryVo itemsQueryVo)throws Exception;
}
4. 整合service
1) 定义service接口
package cn.hr.ssm.service;
import java.util.List;
import cn.hr.ssm.po.ItemsCustom;
import cn.hr.ssm.po.ItemsQueryVo;
public interface ItemsService {
publicList<ItemsCustom> findItemList(ItemsQueryVo itemsQueryVo) throwsException;
}
2) 在spring容器中配置service(applicationContext-service.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 商品管理的service -->
<bean id="itemsService" class="cn.hr.ssm.service.impl.ItemsServiceImpl"/>
</beans>
3) 事务控制(applicationContext-trasaction.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 事务管理
spring使用jdbc的事务控制类
-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- dataSource在applicationContext-dao.xml中已经配置 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="udpate*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="REQUIRED"read-only="true"/>
<tx:method name="get*" propagation="REQUIRED"read-only="true"/>
<tx:method name="select*" propagation="REQUIRED"read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- aop -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(*cn.hr.ssm.service.impl.*.*(..))"/>
</aop:config>
</beans>
5. 整合springmvc
1) springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 扫描controller -->
<context:component-scan base-package="cn.hr.ssm.controller"></context:component-scan>
<!-- 使用mvc:annotation-driven代替注解映射器和注解适配器 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 试图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
2) 配置前端控制器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"id="WebApp_ID" version="3.1">
<display-name>spring_mybatis0823</display-name>
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
3) 编写controller(就是handler)
package cn.hr.ssm.controller;
import java.util.List;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import cn.hr.ssm.po.ItemsCustom;
import cn.hr.ssm.service.ItemsService;
@Controller
public class ItemsController {
@Autowired
privateItemsService itemsService;
@RequestMapping("/queryItems")
publicModelAndView queryItems() throws Exception{
List<ItemsCustom>itemsList = itemsService.findItemList(null);
ModelAndViewmodelAndView = new ModelAndView();
modelAndView.addObject("itemsList",itemsList);
modelAndView.setViewName("items/itemsList");
returnmodelAndView;
}
}
4) 编写jsp
<%@ page language="java"contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"prefix="fmt" %>
<!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>
<form action="${pageContext.request.contextPath}/item/queryItem.action">
查询条件:
<table width="100%" border="1">
<tr>
<td><input type="submit" value="查询" /></td>
</tr>
</table>
商品列表:
<table width="100%" border="1">
<tr>
<td>商品名称</td>
<td>商品价格</td>
<td>生产日期</td>
<td>商品描述</td>
<td>操作</td>
</tr>
<c:forEach items="${itemsList }" var="item">
<tr>
<td>${item.name}</td>
<td>${item.price}</td>
<td><fmt:formatDate value="${item.creattime}" pattern="yyyy-MM-dd HH:mm:ss" /></td>
<td>${item.detail}</td>
<td><a href="#">修改</a></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
6. 加载spring容器
在web.xml中配置
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>