Spring MVC + MyBatis整合(IntelliJ IDEA环境下)

一些重要的知识:

mybais-spring.jar及其提供的API:

SqlSessionFactoryBean:

SqlSessionFactory是由SqlSessionFactoryBuilder产生的,
Spring整合MyBats时SqlSessionFactoryBean也是由SqlSessionFactoryBuilder生成的。

MapperFactoryBean:

在使用MapperFactoryBean时,有一个Mapper,就需要一个MapperFactoryBean。 
为此,需要基于扫描机制的,MapperScannerConfigurer。具体配置方法略。
只需配置要扫描的包。
将扫描该包下所有的带有@MyBatisRepository的Mapper。

第一阶段,spring整合mybatis

项目目录:

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
       xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:task="http://www.springframework.org/schema/task" 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.2.xsd
           http://www.springframework.org/schema/cache   http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
           http://www.springframework.org/schema/mvc     http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
           http://www.springframework.org/schema/task    http://www.springframework.org/schema/task/spring-task-3.2.xsd
           http://www.springframework.org/schema/tx      http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
       "
       default-lazy-init="true">


    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
        <property name = "url" value = "jdbc:mysql:///test"/>
        <property name = "username" value = "root"/>
        <property name = "password" value = "1234"/>
    </bean>

    <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
          <property name="dataSource" ref = "myDataSource"/>
        <property name = "mapperLocations" value = "classpath:com/rixiang/entity/*.xml"/>
    </bean>

    <bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactory" ref = "sqlSessionFactory"/>
        <property name="basePackage" value = "com.rixiang"/>
        <property name = "annotationClass" value = "com.rixiang.annotation.MyBatisRepository"/>
    </bean>


</beans>

EmpDAO,记得添加@MybatisRepository注解:

package com.rixiang.dao;

import java.util.List;

import com.rixiang.annotation.MyBatisRepository;
import com.rixiang.entity.Emp;

@MyBatisRepository
public interface EmpDAO {
    public List<Emp> findAll();
}
MyBatisRepository:
package com.rixiang.annotation;

import org.springframework.stereotype.Repository;

/**
 * Created by samdi on 2016/3/3.
 */
@Repository
public @interface MyBatisRepository {
    String value() default "";
}

test:

package com.rixiang.test;

import com.rixiang.dao.EmpDAO;
import com.rixiang.entity.Emp;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.util.List;

/**
 * Created by samdi on 2016/3/3.
 */
public class TestEmpDAO {
    @Test
    public void testFindAll() throws IOException {
        String conf = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        EmpDAO mapper = ac.getBean("empDAO",EmpDAO.class);
        List<Emp> list = mapper.findAll();
        for(Emp emp:list){
            System.out.println(emp.getEmpno() + " " + emp.getEname());
        }

    }
}

 第二阶段:SpringMVC+MyBatis:

controller:

package com.rixiang.web;

import java.util.List;

import com.rixiang.dao.EmpDAO;
import com.rixiang.entity.Emp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("emp")
public class EmpListController {
    private EmpDAO dao;
    @Autowired
    public void setDao(EmpDAO dao){
        this.dao = dao;
    }
    @RequestMapping("/list")
    public String execute(Model model){
        List<Emp> list = dao.findAll();
        model.addAttribute("emps",list);
        return "emp_list";
    }
}

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
       xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:task="http://www.springframework.org/schema/task" 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.2.xsd
           http://www.springframework.org/schema/cache   http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
           http://www.springframework.org/schema/mvc     http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
           http://www.springframework.org/schema/task    http://www.springframework.org/schema/task/spring-task-3.2.xsd
           http://www.springframework.org/schema/tx      http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
       "
       default-lazy-init="true">


    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
        <property name = "url" value = "jdbc:mysql:///test"/>
        <property name = "username" value = "root"/>
        <property name = "password" value = "1234"/>
    </bean>

    <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
          <property name="dataSource" ref = "myDataSource"/>
        <property name = "mapperLocations" value = "classpath:com/rixiang/entity/*.xml"/>
    </bean>

    <bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactory" ref = "sqlSessionFactory"/>
        <property name="basePackage" value = "com.rixiang"/>
        <property name = "annotationClass" value = "com.rixiang.annotation.MyBatisRepository"/>
    </bean>

    <context:component-scan base-package="com.rixiang"/>

    <!-- 支持@RequestMapping请求和Controller映射 -->
    <mvc:annotation-driven/>

    <!-- 定义视图解析器viewResolver -->
    <bean id = "viewResolver"
          class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name = "prefix" value = "/WEB-INF/jsp/"/>
        <property name = "suffix" value = ".jsp"/>
    </bean>


</beans>

jsp:

<%@ page language = "java" import = "java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
      <head>
         <title>员工列表示例</title>
      </head>
      
      <body>
          <table border="1">
             <tr>
                 <td>编号</td>
                 <td>姓名</td>
                 <td>工资</td>
                 <td>入职时间</td>
             </tr>
             <c:forEach items="${emps}" var="emp">
             <tr>
                  <td>${emp.empno}</td>
                  <td>${emp.ename}</td>
                  <td>${emp.sal}</td>
                  <td>${emp.hiredate}</td> 
             </tr>
            </c:forEach>
          </table>
      </body>
</html>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

运行:

 

posted on 2016-03-03 15:04  J·Marcus  阅读(1952)  评论(0编辑  收藏  举报

导航