第一步:整合dao层
mybatis 和 spring ,通过 spring 管理 mapper 接口。
使用 mapper 的扫描器自动扫描 mapper 接口 在spring中进行注册。
MConfig.xml
<configuration>
<settings>
<setting name="logImpl" value="LOG4J"/>
<setting name="cacheEnabled" value="true"/>
settings>
<typeAliases>
<package name="com.demo.ssm.po"/>
typeAliases>
<mappers>
<package name="com.demo.ssm.mapper"/>
mappers>
configuration>
applicationContext-dao.xml
配置数据源
配置sqlSessionFactory
配置mapper扫描器
<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/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"
>
<context:property-placeholder location="db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="mybatis/MConfig.xml" />
<property name="dataSource" ref="dataSource"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.demo.ssm.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
bean>
beans>
逆向工程生产po类mapper(单表CRUD)
mybatis-generator.xml
<generatorConfiguration>
<context id="testDb">
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mdb" userId="root" password="root">jdbcConnection>
<javaModelGenerator targetPackage="com.demo.ssm.po" targetProject=".\src\main\java">javaModelGenerator>
<sqlMapGenerator targetPackage="com.demo.ssm.mapper" targetProject=".\src\main\java">sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.demo.ssm.mapper" targetProject=".\src\main\java">javaClientGenerator>
<table tableName="item">table>
<table tableName="user">table>
<table tableName="orderdetail">table>
<table tableName="orders">table>
context>
generatorConfiguration>
Generator.java
public class Generator {
public void generator() throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
List warnings = new ArrayList();
boolean overwrite = true;
File configFile = new File("src/main/resources/generator/generatorConfig.xml");
ConfigurationParser parser = new ConfigurationParser(warnings);
Configuration configuration = parser.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(configuration,callback,warnings);
myBatisGenerator.generate(null);
}
public static void main(String[] args) throws InterruptedException, SQLException, InvalidConfigurationException, XMLParserException, IOException {
Generator generator = new Generator();
generator.generator();
}
}
第二步:整合service层
通过 spring 管理 service 接口。
使用配置方式将 service 接口配置在 spring 配置文件中。
实现事务控制
定义service接口
public interface ItemsService {
//商品查询列表
List findItemsList(ItemsQueryVo itemsQueryVo);
}
实现service接口
public class ItemsServiceImpl implements ItemsService {
@Autowired
private ItemsMapperCustom itemsMapperCustom;
public List findItemsList(ItemsQueryVo itemsQueryVo) {
return itemsMapperCustom.findItemsList(itemsQueryVo);
}
}
service配置
applicationContext-service
<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/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"
>
<bean class="com.demo.ssm.service.impl.ItemsServiceImpl">
bean>
beans>
service事务声明
applicationContext-tranaction.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
>
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<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="update*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="sel*" propagation="SUPPORTS" read-only="true"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.demo.ssm.service.impl.*.*(..))"/>
aop:config>
beans>
第三步:整合springmvc
由于 springmvc 是 spring 的模块 , 不需要整合。
创建 springmcv.xml,配置处理器映射器,适配器,视图解析器
springmvc.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:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"
>
<context:component-scan base-package="com.demo.ssm.controller">context:component-scan>
<mvc:annotation-driven>mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
配置前端控制器
web.xml
<web-app>
<display-name>Archetype Created Web Applicationdisplay-name>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring/applicationContext-*.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>*.actionurl-pattern>
servlet-mapping>
web-app>
编写Controller(handler)
ItemsController.java
@Controller
public class ItemsController {
@Autowired
private ItemsService itemsService;
//商品查询列表
@RequestMapping("/queryItems")
public ModelAndView queryItems(){
List list = itemsService.findItemsList(null);
;
//返回modelAndView
ModelAndView modelAndView = new ModelAndView();
//相当于request的setAttr,在jsp通过itemlist获取数据
modelAndView.addObject("itemsList",list);
//指定试图
//试图解析器中配置了前缀和后缀
// modelAndView.setViewName("WEB-INF/jsp/itemsList.jsp");
modelAndView.setViewName("itemsList");
return modelAndView;
编写jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isELIgnored="false" pageEncoding="UTF-8" %>
<%--
Created by IntelliJ IDEA.
User: v7
Date: 2016/8/13
Time: 12:18
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ItemsListtitle>
head>
<body>
<from 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>
<th>商品名称th>
<th>商品价格th>
<th>生产日期th>
<th>商品描述th>
<th>操作th>
tr>
<c:forEach items="${itemsList}" var="item">
<tr>
<td>${item.name}td>
<td>${item.price}td>
<td>${item.createTime}td>
<td>${item.detail}td>
<td><a href="${pageContext.request.contextPath}/item/editItem.action?id=${item.id}">修改a>td>
tr>
c:forEach>
table>
from>
body>
html>
加载spring容器
将mapper,service,controller加载到spring中
建议使用通配符方法加载spring文件.
在web.xml中,添加spring容器
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring/applicationContext-*.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
所需要的jar包:
数据库驱动包:mysql-5.1
mybatis 的jar包
mybatis 和 spring 整合包
log4j 包
数据库连接池包 c3p0
spring 所以jar包
jstl包
maven pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.demogroupId>
<artifactId>ssmartifactId>
<packaging>warpackaging>
<version>1.0-SNAPSHOTversion>
<name>ssm Maven Webappname>
<url>http://maven.apache.orgurl>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.1version>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.3.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.2.8version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>4.3.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>4.3.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>4.3.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>4.3.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.3.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>4.3.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.5version>
dependency>
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1.2version>
dependency>
<dependency>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-coreartifactId>
<version>1.3.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
dependencies>
<build>
<finalName>ssmfinalName>
<plugins>
<plugin>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-maven-pluginartifactId>
<version>1.3.2version>
<configuration>
<verbose>trueverbose>
<overwrite>trueoverwrite>
configuration>
plugin>
plugins>
<resources>
<resource>
<directory>
src/main/resources
directory>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.xmlinclude>
includes>
resource>
resources>
build>
project>
db.properties
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mdb?charaterEncoding='UTF-8'&useSSL=true
jdbc.username = root
jdbc.password = root
log4j.properties
# Global logging configuration
#在开发环境下级别设置成DEBUG,生成环境设置成info或error
log4j.rootLogger = debug,stdout
# MyBatis logging configuration...
log4j.logger.test=TRACE
### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n