admin管理员组

文章数量:821227

SpringMVC整合mybatis(终结版)

ssm框架是目前web开发中最流行的框架之一,这个框架快捷方便,搭建完成后是很容易进行项目的开发的。

本文将使用idea作为开发工具,并使用maven进行项目管理,进行ssm框架的搭建。

1. 整合思路

项目需要进行分层,这里分成三成

dao层

dao层需要整合mybatis和spring,实现数据库层的配置
(1)需要的jar包:
- mybatis的jar包
- Mysql数据库驱动
- 数据库连接池
- Mybatis和spring的整合包
- Spring的jar包
(2)配置文化
- mybatis的配置文件:SqlMapConfig.xml
- Spring的配置文件:applicationContext-dao.xml
(3)配置内容
- 数据源
- 数据库连接池
- 配置SqlSessionFactory(mybatis和spring整合包中的)
- 配置mapper文件的扫描器

service层

dao层需要整合mybatis和spring,实现数据库层的配置
(1)需要的jar包:
- Spring的jar包
(2)配置文化
- 业务配置文件:applicationContext-service.xml
- 事务配置文件:applicationContext-trans.xml
(3)配置内容
- 配置一个包扫描器,扫描所有带@Service注解的类。
- 配置一个事务管理器
- 配置tx和切面

view层

dao层需要整合mybatis和spring,实现数据库层的配置
(1)需要的jar包:
- 使用springmvc和spring的jar包
(2)配置文化
- springmvc.xml
- web.xml
(3)配置内容
- 配置注解驱动
- 配置一个视图解析器。
- 包扫描器,@Controller注解
- 配置springmvc的前端控制器
- Spring容器初始化的listener。

2. 整合过程

(1)新建web项目

用idea新建一个maven项目

项目的结构如下图所示:

在main下面新建java文件夹,并设置为source root

(2)修改pom文件

下面修改文件的依赖

<project xmlns=".0.0" xmlns:xsi=""xsi:schemaLocation=".0.0 .xsd"><modelVersion>4.0.0</modelVersion><groupId>com.chen</groupId><artifactId>ssm</artifactId><packaging>war</packaging><version>1.0-SNAPSHOT</version><name>ssm Maven Webapp</name><url>;/url><properties><junit.version>4.12</junit.version><spring.version>4.1.3.RELEASE</spring.version><mybatis.version>3.2.8</mybatis.version><mybatis.spring.version>1.2.2</mybatis.spring.version><mybatis.paginator.version>1.2.15</mybatis.paginator.version><mysql.version>5.1.32</mysql.version><slf4j.version>1.6.4</slf4j.version><jackson.version>2.4.2</jackson.version><druid.version>1.0.9</druid.version><jstl.version>1.2</jstl.version><servlet-api.version>2.5</servlet-api.version><jsp-api.version>2.0</jsp-api.version></properties><dependencies><!-- Jackson Json处理工具包 --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>${jackson.version}</version></dependency><!-- 单元测试 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junit.version}</version><scope>test</scope></dependency><!-- 日志处理 --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>${slf4j.version}</version></dependency><!-- Mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis.version}</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>${mybatis.spring.version}</version></dependency><!-- MySql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version></dependency><!-- 连接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>${druid.version}</version></dependency><!-- Spring --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>${spring.version}</version></dependency><!-- JSP相关 --><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>${jstl.version}</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>${servlet-api.version}</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jsp-api</artifactId><version>${jsp-api.version}</version><scope>provided</scope></dependency></dependencies><build><finalName>${project.artifactId}</finalName><plugins><!-- 资源文件拷贝插件 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-resources-plugin</artifactId><version>2.7</version><configuration><encoding>UTF-8</encoding></configuration></plugin><!-- java编译插件 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.2</version><configuration><source>1.7</source><target>1.7</target><encoding>UTF-8</encoding></configuration></plugin></plugins><pluginManagement><plugins><!-- 配置Tomcat插件 --><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><configuration><port>8080</port><path>/</path></configuration><version>2.2</version></plugin></plugins></pluginManagement></build>
</project>

我们先测试一下项目是否可以运行:

(3)配置文件
先在resource目录下新建配置文件,项目结构如下:


配置文件的内容如下:

SqlMapConfig.xml
这是mybatis的配置文件,开发过程中可能会需要使用

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN"".dtd">
<configuration></configuration>

db.properties
数据库的配置文件

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/chen?characterEncodind=utf-8
jdbc.username = root
jdbc.password = root

applicationContext-dao.xml
dao层的配置,包括数据库连接池,SqlSessionFactory的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""xmlns:context="" xmlns:p=""xmlns:aop="" xmlns:tx=""xmlns:xsi=""xsi:schemaLocation=" .0.xsd .0.xsd .0.xsd  .0.xsd .0.xsd"><!-- 数据库连接池 --><!-- 加载配置文件 --><context:property-placeholder location="classpath:properties/*.properties" /><!-- 数据库连接池 --><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"destroy-method="close"><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><property name="driverClassName" value="${jdbc.driver}" /><property name="maxActive" value="10" /><property name="minIdle" value="5" /></bean><!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 数据库连接池 --><property name="dataSource" ref="dataSource" /><!-- 加载mybatis的全局配置文件 --><property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /><property name="mapperLocations" value="classpath:mapper/*.xml"/></bean><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.chen.mapper"/></bean>
</beans>

applicationContext-service.xml
service配置,配置扫描

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""xmlns:context="" xmlns:p=""xmlns:aop="" xmlns:tx=""xmlns:xsi=""xsi:schemaLocation=" .0.xsd .0.xsd .0.xsd  .0.xsd .0.xsd"><!-- 包扫描器,扫描带@Service注解的类 --><context:component-scan base-package="com.chen.service"></context:component-scan>
</beans>

applicationContext-trans.xml
配置事务,tx是用来自动进行事务控制的

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""xmlns:context="" xmlns:p=""xmlns:aop="" xmlns:tx=""xmlns:xsi=""xsi:schemaLocation=" .0.xsd .0.xsd .0.xsd  .0.xsd .0.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="insert*" propagation="REQUIRED" /><tx:method name="add*" propagation="REQUIRED" /><tx:method name="create*" propagation="REQUIRED" /><tx:method name="delete*" propagation="REQUIRED" /><tx:method name="update*" propagation="REQUIRED" /><tx:method name="find*" propagation="SUPPORTS" read-only="true" /><tx:method name="select*" propagation="SUPPORTS" read-only="true" /><tx:method name="get*" propagation="SUPPORTS" read-only="true" /></tx:attributes></tx:advice><!-- 切面 --><aop:config><aop:advisor advice-ref="txAdvice"pointcut="execution(* com.chen.service.*.*(..))" /></aop:config>
</beans>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""xmlns:xsi="" xmlns:p=""xmlns:context=""xmlns:mvc=""xsi:schemaLocation=" .xsd .0.xsd .xsd"><!-- 配置包扫描器 -->    <context:component-scan base-package="com.chen.controller"></context:component-scan><!-- 配置注解驱动 --><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
配置视图解析器,适配器和前端控制器等

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi=""xmlns="" xmlns:web=".xsd"xsi:schemaLocation=" .xsd"id="taotao" version="2.5"><display-name>ssm</display-name><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><!-- 初始化spring容器 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/applicationContext-*.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 解决post乱码 --><filter><filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- springmvc的前端控制器 --><servlet><servlet-name>taotao-manager</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" --><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/springmvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>taotao-manager</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>

3. 项目测试

下面我们进行项目的测试,首先新建一个数据库chen

/*
Navicat MySQL Data TransferSource Server         : chen
Source Server Version : 50717
Source Host           : localhost:3306
Source Database       : chenTarget Server Type    : MYSQL
Target Server Version : 50717
File Encoding         : 65001Date: 2017-05-22 15:44:10
*/SET FOREIGN_KEY_CHECKS=0;-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(20) NOT NULL,`password` varchar(20) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'chen', 'chen');

使用mybatis-generatoe插件生成pojo和mapper

新建service

package com.chen.service;import com.chen.pojo.User;/*** Created by chen on 2017/5/22.*/
public interface UserService {public User getUserById(int id);
}
package com.chen.service;import com.chen.mapper.UserMapper;
import com.chen.pojo.User;
import com.chen.pojo.UserExample;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.List;/*** Created by chen on 2017/5/22.*/
@Service
public class UserServiceImpl implements UserService {@ResourceUserMapper userManager;@Overridepublic User getUserById(int id) {UserExample userExample = new UserExample();UserExample.Criteria criteria = userExample.createCriteria();criteria.andIdEqualTo(id);List<User> userList = userManager.selectByExample(userExample);User user = null;if(userList != null && userList.size()>0){user = userList.get(0);}return user;}
}

编写controller类

package com.chen.controller;import com.chen.pojo.User;
import com.chen.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import javax.annotation.Resource;/*** Created by chen on 2017/5/22.*/
@Controller
public class UserController {@ResourceUserService userService;@RequestMapping("/user/{id}")@ResponseBodypublic User getUserById(@PathVariable  int id){return userService.getUserById(id);}
}

运行项目

错误总结:
1. pom.xml中的版本要统一,不然会出现问题

  1. mybatis generator工具

  2. 配置数据格式化

    1. 新建一个数据格式化处理类,implements Formatter,并实现相应的处理方法
    2. springmvc进行配置
      (1)
      <mvc:annotation-driven conversion-service="conversionService">
      (2)
<bean id="conversionService"class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><property name="formatters"><list><bean class="com.cvte.chen.formatter.DateFormatter" c:_0="yyyy-MM-dd"/></list></property></bean>
3. 注意事项: 如果没有数据格式化,在进行数据提交时,如果前台数据和后台数据类不匹配,会发生http400错误

4. 配置json数据
1. 客户端发生json数据,后台可以直接通过数据绑定把数据装入实体类中
2. 后台可以通过@ResponseBody来进行json数据返回
使用@ResponseBody进行json数据返回
1. 导入需要的jar包

   <!--jackson--><!-- .fasterxml.jackson.core/jackson-databind --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.8.8</version></dependency>
  2. 配置jackson控制器
<mvc:annotation-driven  conversion-service="conversionService"><mvc:message-converters><bean id="mappingJacksonHttpMessageConverter"class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"><property name="supportedMediaTypes"><list><!--返回字符串格式json--><value>application/json;charset=UTF-8</value></list></property></bean></mvc:message-converters></mvc:annotation-driven>
     3. controller中使用responseBody
【注意: 1、 如果没有导入jar包或者配置控制器,会发生406错误,因为返回的数据类型不匹配2. 如果使用ajax异步进行json数据交互,必须加上responseBody注解,不然ajax会返回404错误@responsebody表示该方法的返回结果直接写入HTTP response body中一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@responsebody后,会直接返回json数据。3. 使用jackson后,如果controller方法直接返回字符串,responseText会出现双引号,例如 responseText:""success""】

4 . 添加Junit
到Juti中进行MockmMvc的配置,MockMvc可以发送请求,进行强求数据的测试
在进行MockMvc获取时,要获取 WebApplicationContext 需要使用其注解@WebApplicationContext 这里要记得导入servlet

<dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency>  

不然会发生下列的错误 :

java.lang.ExceptionInInitializerError
at com.jbo.testapp.AppServletTest.setUp(AppServletTest.java:36)
at junit.framework.TestCase.runBare(TestCase.java:128)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:120)
at junit.framework.TestSuite.runTest(TestSuite.java:230)
at junit.framework.TestSuite.run(TestSuite.java:225)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:96)
at org.apache.maven.surefire.junit.JUnit3Provider.executeTestSet(JUnit3Provider.java:117)
at org.apache.maven.surefire.junit.JUnit3Provider.invoke(JUnit3Provider.java:94)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)Caused by: java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale es_ESat java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1564)at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1387)at java.util.ResourceBundle.getBundle(ResourceBundle.java:773)at javax.servlet.GenericServlet.<clinit>(GenericServlet.java:95)... 24 more
Caused by: java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale es_ESat java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1564)at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1387)at java.util.ResourceBundle.getBundle(ResourceBundle.java:773)at javax.servlet.GenericServlet.<clinit>(GenericServlet.java:95)... 24 more

代码如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring-*.xml")
@WebAppConfiguration
public class AppTests {private MockMvc mockMvc;@ResourceUsertestMapper usertestMapper;@ResourceUsertestService usertestService;@Resourceprivate WebApplicationContext webApplicationContext;@Beforepublic void setUp() {mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();}@Testpublic void simple() throws Exception {System.out.println("test");}}

本文标签: SpringMVC整合mybatis(终结版)