MyBatis 和 Spring 的整合(三)

5. 整合 Spring部分java

    a. 先將 controller、service、dao 創建起來。web

    Controller:UserController.java
spring

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 (只寫實現)sql

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.xmlapache

        注:由於 jackson 的包用的最新的,因此 消息轉換器的 類:MappingJackson2HttpMessageConverterjson

<?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)spring-mvc

<?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 容器管理。
mybatis

<?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 這個類咱們後面再解釋。mvc

<?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);
	}
}

    應該能夠查詢出結果。。。

相關文章
相關標籤/搜索