前几天趁空闲时间整合了下SpringMVC+Mybatis+Druid,这里小记录下,这个Demo是基于Maven构建的,数据源用的是阿里巴巴温少的开源项目Druid,数据库用的是Mysql。
由于eclipse去安装Maven很不方便,也老出错,这里我使用的是Spring Tool Suite(STS,基于 Spring IDE ,提供了其它的一些特性,如 基于 Spring dm Server 的osgi 开发,及其它一些 Spring 项目的支持,如 Spring Roo , Spring Batch 等)。
一、相关JAR包
由于是基于Maven的项目,找起JAR包自然就方便了许多,我们只需要知道JAR的名字或者其中关键字就可以很轻松的把JAR包以及依赖JAR下载下来,需要多少下多少。
这里给出pom的配置文件。
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>SpringMybatis</groupId> 5 <artifactId>SpringMybatis</artifactId> 6 <packaging>war</packaging> 7 <version>0.0.1-SNAPSHOT</version> 8 <name>SpringMybatis Maven Webapp</name> 9 <url>http://maven.apache.org</url> 10 <dependencies> 11 <dependency> 12 <groupId>org.springframework</groupId> 13 <artifactId>spring-core</artifactId> 14 <version>3.2.10.RELEASE</version> 15 </dependency> 16 <dependency> 17 <groupId>org.springframework</groupId> 18 <artifactId>spring-web</artifactId> 19 <version>3.2.10.RELEASE</version> 20 </dependency> 21 <dependency> 22 <groupId>org.springframework</groupId> 23 <artifactId>spring-webmvc</artifactId> 24 <version>3.2.10.RELEASE</version> 25 </dependency> 26 <dependency> 27 <groupId>org.mybatis</groupId> 28 <artifactId>mybatis</artifactId> 29 <version>3.2.8</version> 30 </dependency> 31 <dependency> 32 <groupId>org.mybatis</groupId> 33 <artifactId>mybatis-spring</artifactId> 34 <version>1.1.1</version> 35 </dependency> 36 <dependency> 37 <groupId>mysql</groupId> 38 <artifactId>mysql-connector-java</artifactId> 39 <version>5.0.2</version> 40 </dependency> 41 <dependency> 42 <groupId>junit</groupId> 43 <artifactId>junit</artifactId> 44 <version>4.12</version> 45 <scope>test</scope> 46 </dependency> 47 <dependency> 48 <groupId>com.alibaba</groupId> 49 <artifactId>druid</artifactId> 50 <version>1.0.11</version> 51 </dependency> 52 <dependency> 53 <groupId>log4j</groupId> 54 <artifactId>log4j</artifactId> 55 <version>1.2.17</version> 56 </dependency> 57 </dependencies> 58 <build> 59 <finalName>SpringMybatis</finalName> 60 </build> 61 </project>
由于Maven会把JAR包所依赖的JAR包也一起下载下来,这里我们就不需要逐个去写Spring的相关JAR包。
这里用到了阿里巴巴温少的开源项目Druid的数据源,所以额外的多引入了一个Druid的JAR包。
关于JAR的扩展,如果有需要别的可以到:http://search.maven.org/ 去查找,然后复制到这个配置文件即可,Maven会帮我们自动下载添加。
二、相关配置
spring.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context.xsd 9 http://www.springframework.org/schema/aop 10 http://www.springframework.org/schema/aop/spring-aop.xsd 11 http://www.springframework.org/schema/tx 12 http://www.springframework.org/schema/tx/spring-tx.xsd"> 13 14 <!-- 自动注入 --> 15 <context:component-scan base-package="lcw/service"/> 16 17 18 </beans>
mybatis-spring.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context.xsd 9 http://www.springframework.org/schema/aop 10 http://www.springframework.org/schema/aop/spring-aop.xsd 11 http://www.springframework.org/schema/tx 12 http://www.springframework.org/schema/tx/spring-tx.xsd"> 13 14 <!-- 配置数据源 --> 15 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> 16 <property name="url" value="jdbc:mysql:///test"></property> 17 <property name="username" value="root"></property> 18 <property name="password" value="root"></property> 19 </bean> 20 21 22 <!-- Mybatis文件 --> 23 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 24 <property name="dataSource" ref="dataSource"></property> 25 <property name="mapperLocations" value="classpath:lcw/mapping/*.xml"></property> 26 </bean> 27 28 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 29 <property name="basePackage" value="lcw.dao"></property> 30 <property name="sqlSessionFactoryBeanName" value ="sqlSessionFactory"></property> 31 </bean> 32 33 34 <!-- 事务管理器 --> 35 <bean id="transactionManager" 36 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 37 <property name="dataSource" ref="dataSource"></property> 38 </bean> 39 40 <tx:annotation-driven transaction-manager="transactionManager" /> 41 42 </beans>
springmvc.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation=" 7 http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context-3.0.xsd 11 http://www.springframework.org/schema/mvc 12 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 13 "> 14 15 <!-- 启用spring mvc 注解 --> 16 <context:annotation-config /> 17 18 <!-- 设置使用注解的类所在的jar包 --> 19 <context:component-scan base-package="lcw.controller"></context:component-scan> 20 21 <!-- 完成请求和注解POJO的映射 --> 22 <bean 23 class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 24 25 <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 --> 26 <bean 27 class="org.springframework.web.servlet.view.InternalResourceViewResolver" 28 p:prefix="/" p:suffix=".jsp" /> 29 30 31 </beans>
log4j.properties
1 # 2 # Copyright 2009-2012 the original author or authors. 3 # 4 # Licensed under the Apache License, Version 2.0 (the "License"); 5 # you may not use this file except in compliance with the License. 6 # You may obtain a copy of the License at 7 # 8 # http://www.apache.org/licenses/LICENSE-2.0 9 # 10 # Unless required by applicable law or agreed to in writing, software 11 # distributed under the License is distributed on an "AS IS" BASIS, 12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 # See the License for the specific language governing permissions and 14 # limitations under the License. 15 # 16 17 ### Global logging configuration 18 log4j.rootLogger=DEBUG, stdout 19 20 ### Uncomment for MyBatis logging 21 log4j.logger.org.apache.ibatis=DEBUG 22 23 ### Console output... 24 log4j.appender.stdout=org.apache.log4j.ConsoleAppender 25 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 26 log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
关于model、dao以及mapping的生成方式,在之前的文章《使用Mybatis-Generator自动生成Dao、Model、Mapping相关文件》有提到,这里就不再给出。
UserController.java
1 package lcw.controller; 2 3 import lcw.model.User; 4 import lcw.service.UserServiceI; 5 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Controller; 8 import org.springframework.ui.Model; 9 import org.springframework.web.bind.annotation.RequestMapping; 10 @Controller 11 @RequestMapping("/userController") 12 public class UserController { 13 14 private UserServiceI userService; 15 16 public UserServiceI getUserService() { 17 return userService; 18 } 19 @Autowired 20 public void setUserService(UserServiceI userService) { 21 this.userService = userService; 22 } 23 24 @RequestMapping("/showUser") 25 public String showUser(Model model){ 26 User user=userService.getUserById(1); 27 model.addAttribute("user", user); 28 return "showuser"; 29 } 30 31 }
UserServiceI.java
1 package lcw.service; 2 3 import lcw.model.User; 4 5 public interface UserServiceI { 6 7 public User getUserById(int id); 8 9 }
UserService.java
package lcw.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import lcw.dao.UserMapper; import lcw.model.User; @Service("userService") public class UserService implements UserServiceI { private UserMapper userMapper; public UserMapper getUserMapper() { return userMapper; } @Autowired public void setUserMapper(UserMapper userMapper) { this.userMapper = userMapper; } @Override public User getUserById(int id) { return userMapper.selectByPrimaryKey(id); } }
showuser.jsp
1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 pageEncoding="ISO-8859-1"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 Hello ${user.password} !! 11 </body> 12 </html>
web.xml
1 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 3 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 4 id="WebApp_ID" version="2.5"> 5 6 7 <!-- 解决工程编码过滤器 --> 8 <filter> 9 <filter-name>characterEncodingFilter</filter-name> 10 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 11 <init-param> 12 <param-name>encoding</param-name> 13 <param-value>UTF-8</param-value> 14 </init-param> 15 </filter> 16 <filter-mapping> 17 <filter-name>characterEncodingFilter</filter-name> 18 <url-pattern>/*</url-pattern> 19 </filter-mapping> 20 21 <!-- SpringMVC配置 --> 22 <servlet> 23 <servlet-name>springDispatcherServlet</servlet-name> 24 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 25 <init-param> 26 <param-name>contextConfigLocation</param-name> 27 <param-value>classpath:springmvc.xml</param-value> 28 </init-param> 29 <load-on-startup>1</load-on-startup> 30 </servlet> 31 32 <servlet-mapping> 33 <servlet-name>springDispatcherServlet</servlet-name> 34 <url-pattern>/</url-pattern> 35 </servlet-mapping> 36 37 38 <!-- 配置文件所在位置 --> 39 <context-param> 40 <param-name>contextConfigLocation</param-name> 41 <param-value>classpath:spring.xml,classpath:mybatis-spring.xml</param-value> 42 </context-param> 43 <!-- Spring配置(监听器) --> 44 <listener> 45 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 46 </listener> 47 48 49 50 51 52 </web-app>
看下效果图:
好了,SpringMVC+Mybtis+Druid完美整合~