springmvc和mybaits整合
整合思路
一、整合dao层
mybatis与spring的整合,最终目的是通过spring管理mapper接口.
使用mapper的扫描器自动扫描mapper接口在spring中进行注册。
二、整合Service层
通过spring管理Service接口
使用配置的方式将Service接口配置在spring配置文件中
这一步还需要实现事务控制
三、整合springmvc
由于springmvc是spring的子模块,所有 不需要整合。
环境准备
相关工具版本:
jdk::1.8.0_102
mysql:5.6
开发工具:MyEclipse 14
服务器:apache-tomcat-7.0.42
spring版本:spring-framework-4.2.1.RELEASE-dist
mybatis版本:mybatis-3.4.4
所需jar包:
commons-logging-1.1.1.jar——日志jar
mchange-commons-java-0.2.3.4.jar——c3p0搭配jar
org.aspectj.weaver-1.6.8.RELEASE.jar
org.aopalliance-1.0.0.jar
构建工程
创相关的文件夹
工程结构
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/MyBatis?useUnicode=true&
jdbc.username=root
jdbc.password=123456
log4j.properties
#Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
整合dao
创建相关配置文件
SqlMapConfig.xml
在config文件下创建一个名为mybatis的文件夹,在mybatis文件夹内创建SqlMapConfig.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>
<typeAliases>
<package name="com.ld.ssm.po"/>
</typeAliases>
</configuration>
applicationContext-dao.xml
config文件中创建spring文件夹,在spring文件夹创建applicationContext-dao.xml,这个配置文件中需要配置数据源、SqlSessionFactory以及mapper扫描器。
<?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"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name= "driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ld.ssm.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
逆向工程生成文件
通过逆向工程生成mapper、mapper.xml、po类等文件
逆向工程操作请参考——mybatis逆向工程操作
将逆向工程得到的文件分别拷贝到相应目录下,结果如下
自定义商品查询mapper和相应映射文件
为了提高系统的扩展性,可以对原生po进行扩展,然后对使用包装对象对po类进行包装
扩展类ItemsCustomer .java
package com.ld.ssm.po;
/**
* 商品信息的扩展类
* @author 浪丶荡
*
*/
public class ItemsCustomer extends Items{
}
包装类:ItemsQuerVo.java
package com.ld.ssm.po;
/**
* 商品信息的包装类
* @author 浪丶荡
*
*/
public class ItemsQuerVo{
private Items items;
private ItemsCustomer itemsCustomer;
public ItemsCustomer getItemsCustomer() {
return itemsCustomer;
}
public void setItemsCustomer(ItemsCustomer itemsCustomer) {
this.itemsCustomer = itemsCustomer;
}
public Items getItems() {
return items;
}
public void setItems(Items items) {
this.items = items;
}
}
ItemsMapperCustomer.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.ld.ssm.mapper.ItemsMapperCustomer">
<sql id="query_items_where">
<if test="itemsCustomer!=null">
<if test="itemsCustomer.name!=null and itemsCustomer!=''">
items.name LIKE '%${itemsCustomer.name}%'
</if>
</if>
items.name LIKE '%旺%'
</sql>
<select id="findItemsList" parameterType="com.ld.ssm.po.ItemsQuerVo"
resultType="com.ld.ssm.po.ItemsCustomer">
SELECT * FROM items
<where>
<include refid="query_items_where"></include>
</where>
</select>
</mapper>
ItemsMapperCustom.java
package com.ld.ssm.mapper
import java.util.List
import com.ld.ssm.po.ItemsCustomer
import com.ld.ssm.po.ItemsQuerVo
public interface ItemsMapperCustomer {
//查询商品信息
public List<ItemsCustomer> findItemsList(ItemsQuerVo itemsQuerVo)throws Exception
}
整合Service层
定义接口
package com.ld.ssm.service;
import java.util.List;
import com.ld.ssm.po.ItemsCustomer;
import com.ld.ssm.po.ItemsQuerVo;
/**
* 商品管理Service
* @author 浪丶荡
*
*/
public interface ItemsService {
public List<ItemsCustomer> findItemsList(ItemsQuerVo itemsQuerVo)throws Exception;
}
接口实现
package com.ld.ssm.service.impl
import java.util.List
import org.springframework.beans.factory.annotation.Autowired
import com.ld.ssm.mapper.ItemsMapperCustomer
import com.ld.ssm.po.ItemsCustomer
import com.ld.ssm.po.ItemsQuerVo
import com.ld.ssm.service.ItemsService
public class ItemsServiceImpl implements ItemsService {
//注入itemsMapperCustomer
@Autowired
private ItemsMapperCustomer itemsMapperCustomer
@Override
public List<ItemsCustomer> findItemsList(ItemsQuerVo itemsQuerVo)
throws Exception {
return itemsMapperCustomer.findItemsList(itemsQuerVo)
}
}
创建applicationContext-service.xml
配置Service
<?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"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="itemsService" class="'com.ld.ssm.service.impl.ItemsServiceImpl"></bean>
</beans>
实现事务控制
创建applicationContext-transaction.xml
使用spring的声明式事务控制方法进行配置
<?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"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config >
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.ld.ssm.service.impl.*.*(..))"/>
</aop:config>
</beans>
整合springmvc
创建springmvc.xml文件
springmvc.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"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<mvc:annotation-driven>
</mvc:annotation-driven>
<context:component-scan base-package="com.ld.springmvc.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
配置前端控制器
在web.xml中配置前端控制器
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>beautiful</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>beautiful</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
编写处理器(Controller即Handler)
注解方式开发Controller
package com.ld.ssm.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.ld.ssm.po.ItemsCustomer;
import com.ld.ssm.service.ItemsService;
/**
* 商品的Controller
* @author 浪丶荡
*
*/
@Controller
public class ItemsController {
@Autowired
private ItemsService itemsService;
@RequestMapping("/findItemsList.action")
public ModelAndView findItemsList()throws Exception{
List<ItemsCustomer> itemsList = itemsService.findItemsList(null);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("itemsList", itemsList);
modelAndView.setViewName("/items/itemsList");
return modelAndView;
}
}
编写前端页面
位置:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
response.setContentType("text/html;charset = GB2312");
request.setCharacterEncoding("gb2312");
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>查询商品列表</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<form action="${pageContext.request.contextPath }/item/queryItem.action" method="post">
查询条件
<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.createtime }" pattern="yyyy-MM-dd HH:mm:ss" /></td>
<td>${item.detail }</td>
<td><a href="${pageContext.request.contentType }/item/editItem.action?id=${item.id}">修改</a></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
加载spring容器
加载下列文件
添加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>
调试:访问路径
http://127.0.0.1/springmvc_mybatis/findItemsList.action
结果
终于还是出来了!
需要源码的加QQ群:511906138联系管理员