标签:
1 <projectxmlns="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/xsd/maven-4.0.0.xsd"> 2 <modelVersion>4.0.0</modelVersion> 3 <groupId>springDemo</groupId> 4 <artifactId>springDemo</artifactId> 5 <version>0.0.1-SNAPSHOT</version> 6 <packaging>war</packaging> 7 <name>springDemo</name> 8 <url>http://maven.apache.org</url> 9 <description>搭建Spring+SpringMVC+mybatis开发环境</description> 10 <properties> 11 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 12 <!-- spring版本号 --> 13 <spring.version>3.2.4.RELEASE</spring.version> 14 <org.aspectj.version>1.7.3</org.aspectj.version> 15 <!-- mybatis版本号 --> 16 <mybatis.version>3.2.4</mybatis.version> 17 <!-- log4j日志文件管理包版本 --> 18 <slf4j.version>1.6.6</slf4j.version> 19 <log4j.version>1.2.12</log4j.version> 20 </properties> 21 <dependencies> 22 <!-- spring核心包 --> 23 <!-- springframe start --> 24 <dependency> 25 <groupId>org.springframework</groupId> 26 <artifactId>spring-core</artifactId> 27 <version>${spring.version}</version> 28 </dependency> 29 <dependency> 30 <groupId>org.springframework</groupId> 31 <artifactId>spring-web</artifactId> 32 <version>${spring.version}</version> 33 </dependency> 34 <dependency> 35 <groupId>org.springframework</groupId> 36 <artifactId>spring-oxm</artifactId> 37 <version>${spring.version}</version> 38 </dependency> 39 <dependency> 40 <groupId>org.springframework</groupId> 41 <artifactId>spring-tx</artifactId> 42 <version>${spring.version}</version> 43 </dependency> 44 <dependency> 45 <groupId>org.springframework</groupId> 46 <artifactId>spring-jdbc</artifactId> 47 <version>${spring.version}</version> 48 </dependency> 49 <dependency> 50 <groupId>org.springframework</groupId> 51 <artifactId>spring-webmvc</artifactId> 52 <version>${spring.version}</version> 53 </dependency> 54 <dependency> 55 <groupId>org.springframework</groupId> 56 <artifactId>spring-aop</artifactId> 57 <version>${spring.version}</version> 58 </dependency> 59 <dependency> 60 <groupId>org.springframework</groupId> 61 <artifactId>spring-context-support</artifactId> 62 <version>${spring.version}</version> 63 </dependency> 64 <dependency> 65 <groupId>org.springframework</groupId> 66 <artifactId>spring-test</artifactId> 67 <version>${spring.version}</version> 68 </dependency> 69 <dependency> 70 <groupId>org.aspectj</groupId> 71 <artifactId>aspectjweaver</artifactId> 72 <version>${org.aspectj.version}</version> 73 </dependency> 74 <dependency> 75 <groupId>org.aspectj</groupId> 76 <artifactId>aspectjrt</artifactId> 77 <version>${org.aspectj.version}</version> 78 </dependency> 79 <dependency> 80 <groupId>cglib</groupId> 81 <artifactId>cglib</artifactId> 82 <version>2.2.2</version> 83 </dependency> 84 <dependency> 85 <groupId>cglib</groupId> 86 <artifactId>cglib-nodep</artifactId> 87 <version>2.2.2</version> 88 </dependency> 89 <!-- springframe end --> 90 <!-- mybatis核心包 --> 91 <dependency> 92 <groupId>org.mybatis</groupId> 93 <artifactId>mybatis</artifactId> 94 <version>${mybatis.version}</version> 95 </dependency> 96 <!-- mybatis/spring包 --> 97 <dependency> 98 <groupId>org.mybatis</groupId> 99 <artifactId>mybatis-spring</artifactId> 100 <version>1.2.2</version> 101 </dependency> 102 <!-- mysql驱动包 --> 103 <dependency> 104 <groupId>mysql</groupId> 105 <artifactId>mysql-connector-java</artifactId> 106 <version>5.1.29</version> 107 </dependency> 108 <!-- junit测试包 --> 109 <dependency> 110 <groupId>junit</groupId> 111 <artifactId>junit</artifactId> 112 <version>4.11</version> 113 <scope>test</scope> 114 </dependency> 115 <!-- 阿里巴巴数据源包 --> 116 <dependency> 117 <groupId>com.alibaba</groupId> 118 <artifactId>druid</artifactId> 119 <version>1.0.2</version> 120 </dependency> 121 <dependency> 122 <groupId>org.apache.commons</groupId> 123 <artifactId>commons-lang3</artifactId> 124 <version>3.1</version> 125 </dependency> 126 <dependency> 127 <groupId>commons-dbcp</groupId> 128 <artifactId>commons-dbcp</artifactId> 129 <version>1.4</version> 130 </dependency> 131 <!-- json数据 --> 132 <dependency> 133 <groupId>org.codehaus.jackson</groupId> 134 <artifactId>jackson-mapper-asl</artifactId> 135 <version>1.9.13</version> 136 </dependency> 137 <dependency> 138 <groupId>commons-lang</groupId> 139 <artifactId>commons-lang</artifactId> 140 <version>2.6</version> 141 </dependency> 142 <dependency> 143 <groupId>javax.servlet</groupId> 144 <artifactId>jstl</artifactId> 145 <version>1.2</version> 146 </dependency> 147 <dependency> 148 <groupId>javax.servlet</groupId> 149 <artifactId>servlet-api</artifactId> 150 <version>2.5</version> 151 </dependency> 152 <dependency> 153 <groupId>org.apache.velocity</groupId> 154 <artifactId>velocity</artifactId> 155 <version>1.7</version> 156 </dependency> 157 <dependency> 158 <groupId>org.apache.velocity</groupId> 159 <artifactId>velocity-tools</artifactId> 160 <version>2.0</version> 161 </dependency> 162 <!-- 日志文件管理包 --> 163 <!-- log start --> 164 <dependency> 165 <groupId>log4j</groupId> 166 <artifactId>log4j</artifactId> 167 <version>${log4j.version}</version> 168 </dependency> 169 <dependency> 170 <groupId>org.slf4j</groupId> 171 <artifactId>slf4j-api</artifactId> 172 <version>${slf4j.version}</version> 173 </dependency> 174 <dependency> 175 <groupId>org.slf4j</groupId> 176 <artifactId>slf4j-log4j12</artifactId> 177 <version>${slf4j.version}</version> 178 </dependency> 179 <!-- log end --> 180 </dependencies> 181 <build> 182 <plugins> 183 <plugin> 184 <artifactId>maven-compiler-plugin</artifactId> 185 <version>2.3.2</version> 186 <configuration> 187 <source>1.6</source> 188 <target>1.6</target> 189 </configuration> 190 </plugin> 191 <plugin> 192 <artifactId>maven-war-plugin</artifactId> 193 <version>2.2</version> 194 <configuration> 195 <version>3.0</version> 196 <failOnMissingWebXml>false</failOnMissingWebXml> 197 </configuration> 198 </plugin> 199 </plugins> 200 </build> 201 </project>
(2)配置spring-mybatis.xml文件
1 jdbc_driverClassName=com.mysql.jdbc.Driver 2 jdbc_url=jdbc:mysql://localhost:3306/weixin?useUnicode=true&characterEncoding=utf-8 3 jdbc_username=root 4 jdbc_password= 5 #定义初始连接数 6 initialSize=0 7 #定义最大连接数 8 maxActive=20 9 #定义最大空闲 10 maxIdle=20 11 #定义最小空闲 12 minIdle=1 13 #定义最长等待时间 14 maxWait=60000
现在开始配置spring-mybatis.xml文件。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beansxmlns="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="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-3.1.xsd 10 http://www.springframework.org/schema/mvc 11 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 12 <!-- 自动扫描 --> 13 <context:component-scanbase-package="com.aheizi"/> 14 <!-- 引入配置文件 --> 15 <beanid="propertyConfigurer" 16 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 17 <propertyname="location"value="classpath:properties/jdbc.properties"/> 18 </bean> 19 <beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource" 20 destroy-method="close"> 21 <propertyname="driverClassName"value="${driver}"/> 22 <propertyname="url"value="${url}"/> 23 <propertyname="username"value="${username}"/> 24 <propertyname="password"value="${password}"/> 25 <!-- 初始化连接大小 --> 26 <propertyname="initialSize"value="${initialSize}"></property> 27 <!-- 连接池最大数量 --> 28 <propertyname="maxActive"value="${maxActive}"></property> 29 <!-- 连接池最大空闲 --> 30 <propertyname="maxIdle"value="${maxIdle}"></property> 31 <!-- 连接池最小空闲 --> 32 <propertyname="minIdle"value="${minIdle}"></property> 33 <!-- 获取连接最大等待时间 --> 34 <propertyname="maxWait"value="${maxWait}"></property> 35 </bean> 36 <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> 37 <beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"> 38 <propertyname="dataSource"ref="dataSource"/> 39 <!-- 自动扫描mapping.xml文件 --> 40 <propertyname="mapperLocations"value="classpath:com/aheizi/mapping/*.xml"></property> 41 </bean> 42 <!-- DAO接口所在包名,Spring会自动查找其下的类 --> 43 <beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"> 44 <propertyname="basePackage"value="com.aheizi.dao"/> 45 <propertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"></property> 46 </bean> 47 <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> 48 <beanid="transactionManager" 49 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 50 <propertyname="dataSource"ref="dataSource"/> 51 </bean> 52 </beans>
这里我们已经完成了spring和mybatis的整合。下面配置log4j和JUnit:
1 #定义LOG输出级别 2 log4j.rootLogger=INFO,Console,File 3 #定义日志输出目的地为控制台 4 log4j.appender.Console=org.apache.log4j.ConsoleAppender 5 log4j.appender.Console.Target=System.out 6 #可以灵活地指定日志输出格式,下面一行是指定具体的格式 7 log4j.appender.Console.layout = org.apache.log4j.PatternLayout 8 log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n 9 #文件大小到达指定尺寸的时候产生一个新的文件 10 log4j.appender.File = org.apache.log4j.RollingFileAppender 11 #指定输出目录 12 log4j.appender.File.File = logs/ssm.log 13 #定义文件最大大小 14 log4j.appender.File.MaxFileSize = 10MB 15 # 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志 16 log4j.appender.File.Threshold = ALL 17 log4j.appender.File.layout = org.apache.log4j.PatternLayout 18 log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
(4)JUnit测试
1 DROP TABLE IF EXISTS `user_t`; 2 CREATE TABLE `user_t`( 3 `id`int(11) NOT NULL AUTO_INCREMENT, 4 `user_name` varchar(40) NOT NULL, 5 `password` varchar(255) NOT NULL, 6 `age`int(4) NOT NULL, 7 PRIMARY KEY (`id`) 8 ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; 9 /*Data for the table `user_t` */ 10 insert into`user_t`(`id`,`user_name`,`password`,`age`) values (1,‘测试‘,‘sfasgfaf‘,24);
创建实体类,Mybatis映射文件,以及DAO接口。(注:也可以使用MyBatis Generator自动创建代码,详情见http://blog.csdn.net/zhshulin/article/details/23912615)
1 package com.aheizi.domain; 2 publicclassUser{ 3 privateInteger id; 4 privateString userName; 5 privateString password; 6 privateInteger age; 7 publicInteger getId(){ 8 return id; 9 } 10 publicvoid setId(Integer id){ 11 this.id = id; 12 } 13 publicString getUserName(){ 14 return userName; 15 } 16 publicvoid setUserName(String userName){ 17 this.userName = userName ==null?null: userName.trim(); 18 } 19 publicString getPassword(){ 20 return password; 21 } 22 publicvoid setPassword(String password){ 23 this.password = password ==null?null: password.trim(); 24 } 25 publicInteger getAge(){ 26 return age; 27 } 28 publicvoid setAge(Integer age){ 29 this.age = age; 30 } 31 }
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3 <mappernamespace="com.aheizi.dao.UserMapper"> 4 <resultMapid="BaseResultMap"type="com.aheizi.domain.User"> 5 <idcolumn="id"property="id"jdbcType="INTEGER"/> 6 <resultcolumn="user_name"property="userName"jdbcType="VARCHAR"/> 7 <resultcolumn="password"property="password"jdbcType="VARCHAR"/> 8 <resultcolumn="age"property="age"jdbcType="INTEGER"/> 9 </resultMap> 10 <sqlid="Base_Column_List"> 11 id, user_name, password, age 12 </sql> 13 <selectid="selectByUserId"resultMap="BaseResultMap"parameterType="java.lang.Integer"> 14 select 15 <includerefid="Base_Column_List"/> 16 from user_t 17 where id = #{id,jdbcType=INTEGER} 18 </select> 19 </mapper>
1 package com.aheizi.Dao; 2 import com.aheizi.domain.User; 3 publicinterfaceUserMapper{ 4 int deleteByPrimaryKey(Integer id); 5 int insert(User record); 6 int insertSelective(User record); 7 User selectByPrimaryKey(Integer id); 8 int updateByPrimaryKeySelective(User record); 9 int updateByPrimaryKey(User record); 10 }
1 package com.aheizi.service; 2 import com.aheizi.domain.User; 3 public interface UserService { 4 public User getUserById(int userId); 5 }
1 package com.aheizi.service.impl; 2 import javax.annotation.Resource; 3 import org.springframework.stereotype.Service; 4 import com.aheizi.dao.UserMapper; 5 import com.aheizi.domain.User; 6 import com.aheizi.service.UserService; 7 @Service("userService") 8 public class UserServiceImpl implements UserService { 9 @Resource 10 private UserMapper userDao; 11 @Override 12 public User getUserById(int userId) { 13 // TODO Auto-generated method stub 14 return userDao.selectByUserId(userId); 15 } 16 }
1 package com.aheizi.testmybatis; 2 import javax.annotation.Resource; 3 import org.apache.log4j.Logger; 4 import org.junit.Before; 5 import org.junit.Test; 6 import org.springframework.context.ApplicationContext; 7 import org.springframework.context.support.ClassPathXmlApplicationContext; 8 import com.aheizi.domain.User; 9 import com.aheizi.service.UserService; 10 publicclassTestMybatis{ 11 privatestaticLogger logger =Logger.getLogger(TestSpringDemo.class); 12 privateApplicationContext ac =null; 13 @Resource 14 privateUserService userService =null; 15 @Before 16 publicvoid before(){ 17 ac =newClassPathXmlApplicationContext("config/spring-mybatis.xml"); 18 userService =(UserService) ac.getBean("userService"); 19 } 20 @Test 21 publicvoid test1(){ 22 User user = userService.getUserById(1); 23 logger.info("userName"+ user.getUserName()); 24 } 25 }
1 [org.springframework.context.support.ClassPathXmlApplicationContext] - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@51de0b09: startup date [Tue Sep 01 18:06:48 CST 2015]; root of context hierarchy 2 [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [config/spring-mybatis.xml] 3 [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] - Loading properties file from class path resource [properties/jdbc.properties] 4 [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@524decad: defining beans [userService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,propertyConfigurer,dataSource,sqlSessionFactory,org.mybatis.spring.mapper.MapperScannerConfigurer#0,transactionManager,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,userMapper]; root of factory hierarchy 5 [com.aheizi.testmybatis.TestSpringDemo] - userName测试
1 package com.aheizi.testmybatis; 2 import javax.annotation.Resource; 3 import org.apache.log4j.Logger; 4 import org.junit.Test; 5 import org.junit.runner.RunWith; 6 import org.springframework.test.context.ContextConfiguration; 7 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 8 import com.aheizi.domain.User; 9 import com.aheizi.service.UserService; 10 @RunWith(SpringJUnit4ClassRunner.class)//表示继承了SpringJUnit4ClassRunner类 11 @ContextConfiguration(locations ={"classpath*:config/spring-mybatis.xml"}) 12 publicclassTestSpringDemo{ 13 privatestaticLogger logger =Logger.getLogger(TestSpringDemo.class); 14 @Resource 15 privateUserService userService =null; 16 @Test 17 publicvoid test1(){ 18 User user = userService.getUserById(1); 19 logger.info("userName"+ user.getUserName()); 20 } 21 }
1 [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from URL [file:/D:/workspace/springDemo/target/classes/config/spring-mybatis.xml] 2 [org.springframework.context.support.GenericApplicationContext] - Refreshing org.springframework.context.support.GenericApplicationContext@58d7330d: startup date [Tue Sep 01 18:15:56 CST 2015]; root of context hierarchy 3 [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] - Loading properties file from class path resource [properties/jdbc.properties] 4 [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6a9b65cc: defining beans [userService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,propertyConfigurer,dataSource,sqlSessionFactory,org.mybatis.spring.mapper.MapperScannerConfigurer#0,transactionManager,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,userMapper]; root of factory hierarchy 5 [com.aheizi.testmybatis.TestSpringDemo] - userName测试 6 [org.springframework.context.support.GenericApplicationContext] - Closing org.springframework.context.support.GenericApplicationContext@58d7330d: startup date [Tue Sep 01 18:15:56 CST 2015]; root of context hierarchy 7 [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6a9b65cc: defining beans [userService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,propertyConfigurer,dataSource,sqlSessionFactory,org.mybatis.spring.mapper.MapperScannerConfigurer#0,transactionManager,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,userMapper]; root of factory hierarchy
搭建Spring + SpringMVC + Mybatis框架之二(整合Spring和Mybatis)
标签:
原文地址:http://www.cnblogs.com/aheizi/p/4779232.html