码迷,mamicode.com
首页 > 编程语言 > 详细

MyBatis 和 Spring 的整合(三)

时间:2015-11-17 13:06:16      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:

5. 整合 Spring部分

    a. 先将 controller、service、dao 建立起来。

    Controller:UserController.java

package ssm.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import ssm.model.User;
import ssm.service.UserManagerService;

@Controller
@RequestMapping("/userManage")  //模块路径
public class UserController {
	@Autowired
	UserManagerService userManagerService;
	
	@RequestMapping(value="/findUserById", method=RequestMethod.GET)
	public String findUserById(Model model, @RequestParam(required=true) Integer userId) throws Exception {
		
		User user = userManagerService.findUserById(userId);
		System.out.println(user);
		
		model.addAttribute("user", user);
		
		return "userManage/userDetail";
	}
	
	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}
}

    UserManagerService 接口和实现:  UserManagerServiceImpl.java (只写实现)

package ssm.service.impl;

import ssm.dao.UserDAO;
import ssm.model.User;
import ssm.service.UserManagerService;

public class UserManagerServiceImpl implements UserManagerService {
	
	private UserDAO userDAO;
	
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	@Override
	public User findUserById(int id) throws Exception {
		//调用 orderMapper 获取用户信息
		return userDAO.findUserById(id);
	}
}

    UserDAO接口和实现(UserDAOImpl.java):继承的 SqlSessionDaoSupport 用来为 DAO 提供 SqlSession。

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;

import ssm.dao.UserDAO;
import ssm.mapper.UserMapper;
import ssm.model.User;

public class UserDAOImpl extends SqlSessionDaoSupport implements UserDAO {
	@Autowired
	private UserMapper userMapper;

	@Override
	public User findUserById(int userId) throws Exception {
		User user = null;
		user = userMapper.findUserById(userId);
		
		return user;
	}
}

    b. 完成 Spring 的配置文件:前面 web.xml 中配置的 DispatcherServlet contextConfigLocation:spring-servlet.xml

        注:因为 jackson 的包用的最新的,所以 消息转换器的 类:MappingJackson2HttpMessageConverter

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/util
		http://www.springframework.org/schema/util/spring-util.xsd ">
		
    <!-- 组件扫描 -->
	<context:component-scan base-package="ssm.controller" />

	<!-- 启动注解驱动 -->
	<!-- <mvc:annotation-driven /> -->
	
	<!-- 也可以自己配置映射器和适配器,替换上面的annotion-driven -->
	<!-- 映射器 -->
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
	<!-- 适配器 -->
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
			<util:list id="messageConverter">
				<ref bean="jsonHttpMessageConverter"/>
			</util:list>
		</property>
	</bean>
	
	<!-- 消息转换器 -->
	<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
	
	<!-- 视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

    c. 还记得之前在 mybatis 的 SqlMapConfig.xml 中配置的 数据库连接池吗?现在我们要把它交给 spring 来管理:将     SqlMapConfig.xml  中引用的 properties、 environments 等注释掉。并且在 resources/spring 下新建 applicationContext.xml 配置文件。如下:(因为用的 spring 4.2.2,database class 用的是 org.apache.commons.dbcp2.BasicDataSource, 并且属性 maxTotal 较早的版本是 maxActive)

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.1.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.1.xsd ">
	
	<context:property-placeholder location="classpath:db.properties"/>
	
	<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${oracle.driver}" />
		<property name="url" value="${oracle.url}" />
		<property name="username" value="${oracle.username}" />
		<property name="password" value="${oracle.password}" />
		<property name="maxTotal" value="30" />
		<property name="maxIdle" value="5" />
	</bean>
	
</beans>

    d. service 配置文件: applicationContext-service.xml,将 service Bean 交给 spring 容器管理。

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.1.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.1.xsd ">
	
	<bean id="userManagerService" class="ssm.service.impl.UserManagerServiceImpl">
	        <!-- 将 DAO 注入 service -->
		<property name="userDAO" ref="userDAO" />
	</bean>
</beans>

    dao 配置文件:其中 关于 org.mybatis.spring.mapper.MapperScannerConfigurer 这个类我们后面再解释。

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.1.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.1.xsd ">
	
	<!-- 配置 SqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
	</bean>
	
	<!-- mapper扫描器 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="ssm.mapper" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>
	
	<bean id="userDAO" class="ssm.dao.impl.UserDAOImpl">
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>
</beans>

OK! Spring 的配置也完成了,那么写一个测试类 test 一下:SpringMyBatisTest.java

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import ssm.model.User;
import ssm.service.UserManagerService;

public class SpringMyBatisTest {

	public static void main(String[] args) throws Exception {
		
		//加载配置文件
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"classpath:mybatis/SqlMapConfig.xml",
				"classpath:spring/applicationContext.xml",
				"classpath:spring/applicationContext-dao.xml",
				"classpath:spring/applicationContext-service.xml");

		UserManagerService service = (UserManagerService) ctx.getBean("userManagerService");

		User user = service.findUserById(100101);

		System.out.println("User ---- " + user);
	}
}

    应该可以查询出结果。。。

MyBatis 和 Spring 的整合(三)

标签:

原文地址:http://my.oschina.net/u/1757476/blog/531267

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!