项目环境:
- spring-4.3.7 + mybatis-3.3.0 + maven-3.3.9 + oracle11g
1. 首先使用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.0</modelVersion> <groupId>com.ssm</groupId> <artifactId>ssm</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <properties> <project.build.sourceEncoding>utf-8</project.build.sourceEncoding> </properties> <!-- spring官方提供的依赖管理器,便于统一管理 --> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-framework-bom</artifactId> <version>4.3.7.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- 引入web工程所需的依赖 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <!-- 引入测试所需的依赖,使用spring4.3.x版本整合需要引入junit4.12及以上 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope>i </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <!-- 整合SpringMVC会自动引入其他所需的spring核心依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <!-- 添加mybatis依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!-- 添加mybatis与sping整合依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <!-- 数据库依赖,使用oracle需要手动将oracle安装到本地maven仓库(版权问题) --> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc7</artifactId> <version>12.1.0.2</version> </dependency> <!-- dbcp数据库连接池依赖 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- logback日志依赖 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.7</version> </dependency> <!-- 添加JSTL标签库 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies></project>
2. 搭建mybatis环境:
- 使用mapper代理的方式:定义一个接口EmployeeDao :
public interface EmployeeDao { Employee selectById(Integer id); List<Employee> selectAll(); int save(Employee emp); int update(Employee emp); int delete(Integer id);}
- 对应的mapper映射文件:
<?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"><!-- namespace一定要对应接口的全类名 --><mapper namespace="com.ssm.dao.EmployeeDao"> <select id="selectById" parameterType="int" resultType="employee"> select empno, ename, job, mgr, hiredate, sal, comm, deptno from emp where empno = #{empno} </select> <!-- mybatis会自动将结果集映射为employee的List --> <select id="selectAll" resultType="employee"> select empno, ename, job, mgr, hiredate, sal, comm, deptno from emp </select> <update id="save" parameterType="employee"> insert into emp(empno, ename, job, mgr, hiredate, sal, comm) values(#{empno}, #{ename}, #{job}, #{mgr}, #{hireDate}, #{sal}, #{comm}) </update> <update id="update" parameterType="employee"> update emp set ename = #{ename}, job = #{job}, mgr = #{mgr}, hiredate = #{hireDate}, sal = #{sal}, comm = #{comm} where empno = #{empno} </update> <delete id="delete" parameterType="int"> delete from emp where empno = #{empno} </delete></mapper>
3. spring整合mybatis
- 日志logback.xml:
<?xml version="1.0" encoding="UTF-8"?><configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{HH:mm:ss} [%thread] %-5level %logger{36} - %msg %n </Pattern> </layout> </appender> <logger name="com.base22" level="TRACE" /> <root level="debug"> <appender-ref ref="STDOUT" /> </root></configuration>
- jdbc.properties:
jdbc.driverClass=oracle.jdbc.OracleDriverjdbc.url=jdbc:oracle:thin:@localhost:1521:orcljdbc.username=scottjdbc.password=scott
- spring-mybatis.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" 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"> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 配置c3p0数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- 注入MyBatis的SqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!-- 配置MyBatis全局配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- 扫描mapper需要的映射文件,可以使用通配符 --> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> <!-- 扫描entity包,使用别名 --> <property name="typeAliasesPackage" value="com.ssm.entity"></property> </bean> <!-- 配置需要扫描的Dao接口,动态实现,并注入到spring的IOC容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 不建议注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> <!-- 配置需要扫描的Dao接口的包 --> <property name="basePackage" value="com.ssm.dao"></property> </bean> <!-- 扫描service层--> <context:component-scan base-package="com.ssm.service"></context:component-scan> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 开启注解式事务驱动 --> <tx:annotation-driven transaction-manager="transactionManager"/></beans>
dao层测试:
//使用SpringRunner需要junit4.12及以上支持@RunWith(SpringRunner.class)@ContextConfiguration("classpath:spring-dao.xml")public class EmployeeDaoTest { private Logger log = LoggerFactory.getLogger(this.getClass()); @Autowired private EmployeeDao employeeDao; @Test public void testSelectById() { Employee emp = employeeDao.selectById(7369); log.info("emp: {}", emp); } @Test public void testSelectAll() { List<Employee> list = employeeDao.selectAll(); for(Employee emp : list) { log.info("list_emp: {}", emp); } } @Test public void testSave() { Employee emp = new Employee(1000, "ssm", "Java", 1000, 500.0, 1000.0, new Date()); int saveCount = employeeDao.save(emp); log.info("saveCount: {}", saveCount); } @Test public void testUpdate() { Employee emp = employeeDao.selectById(1000); emp.setHireDate(new Date()); int updateCount = employeeDao.update(emp); log.info("updateCount: {}", updateCount); } @Test public void testDelete() { int deleteCount = employeeDao.delete(1000); log.info("deleteCount: {}", deleteCount); }}
4. spring整合springmvc
- 首先需要在web.xml中配置springmvc的核心Servlet控制器:
<servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-*.xml</param-value> </init-param> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <!-- 不要写成"/*" --> <url-pattern>/</url-pattern></servlet-mapping>
- 写自己的handler
@Controller@RequestMapping("/emp")public class EmployeeHandler { @Autowired private EmployeeService employeeService; @RequestMapping(value="/list") public String list(HttpServletRequest request) { List<Employee> list = employeeService.selectAll(); request.setAttribute("employees", list); return "list"; } @RequestMapping(value="/selectById") public String selectById(Integer id, HttpServletRequest request) { Employee emp = employeeService.selectById(id); request.setAttribute("employee", emp); return "details"; } @RequestMapping(value="/add") public String add(Employee emp) { return "add"; } @RequestMapping(value="/save") public String save(Employee emp) { employeeService.save(emp); return "redirect:list"; } @RequestMapping(value="/update") public String update(Employee emp) { employeeService.update(emp); return "redirect:list"; } @RequestMapping(value="/delete") public String delete(Integer id) { employeeService.delete(id); return "redirect:list"; }}
- 配置spring-web.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" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scanbase-package="com.ssm.web"></context:component-scan> <!-- 开启SpringMVC注解模式 简化配置: 1. 自动注册DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter 2. 提供一系列默认支持:数据绑定、日期格式转换,xml&json支持 --> <mvc:annotation-driven/> <!-- 静态资源默认servlet配置 1. 加入对静态资源的处理:js,css,gif 2. 允许使用"/"做整体映射 --> <mvc:default-servlet-handler/> <!-- 配置视图解析器 --> <bean id="" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean></beans>