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

原文: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>

运行:

 

时间: 2024-09-13 08:26:00

Spring MVC + MyBatis整合(IntelliJ IDEA环境下)的相关文章

我用spring mvc+mybatis整合为什么出这个错误,是不是路径错误?我是新手,请大神指教

问题描述 我用spring mvc+mybatis整合为什么出这个错误,是不是路径错误?我是新手,请大神指教 org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [D:JAVANewWorkspace.metadata.pluginsorg.eclipse.wst.server.coretmp0wtpwebappsstudent

Spring+Velocity+Mybatis整合笔记(step by step)

一.开发工具 开发过程中使用的操作系统是OS X,关于软件安装的问题请大家移步高效的Mac环境设置. 本文是我对自己学习过程的一个回顾,应该还有不少问题待改进,例如目录的设置.编码习惯和配置文件的处理等,请大家多多指正. 文中用到的开发工具列举如下: JDK 1.7.0_79 Intellij IDEA Ultimate 14 Mysql 5.6.25 Maven 3 Git.SourceTree 二.新建工程 1. 新建空的maven工程 第一步新建工程,选择Maven工程,如图1所示.注意,

浅析Spring和MyBatis整合及逆向工程_java

spring和mybatis整合 整合思路 需要spring通过单例方式管理SqlSessionFactory. spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession.(spring和mybatis整合自动完成) 持久层的mapper都需要由spring进行管理. 整合环境 创建一个新的java工程(接近实际开发的工程结构) jar包: mybatis3.2.7的jar包 spring3.2.0的jar包 mybatis和spring的整合

请教spring 3+mybatis整合出错问题

问题描述 请教spring 3+mybatis整合出错问题 spring 3+mybatis3+spring security整合,我的包和层次结构如下:采用的是按照模块分层, 每层有dao,sevrice,web三个目录,所有的实体类放在model文件夹中 security包中,有dao,service,web三个目录,其中 SecurityDao.java @MyBatisDao public interface SecurityDao extends BaseMapper { // 获得群

spring- Jersey+Spring mvc + mybatis 实现rest 接口

问题描述 Jersey+Spring mvc + mybatis 实现rest 接口 java.lang.IncompatibleClassChangeError: Implementing class at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineC

spring springmvc mybatis整合时,tomcat启动正常,查询数据库时报错

问题描述 spring springmvc mybatis整合时,tomcat启动正常,查询数据库时报错 Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Access denied for user 'root'@'localhost' (using password: YE

junit-搭建SSM框架进行JUnit测试spring和mybatis整合

问题描述 搭建SSM框架进行JUnit测试spring和mybatis整合 log4j:WARN No such property [converssionPattern] in org.apache.log4j.PatternLayout. log4j:WARN No such property [macFileSize] in org.apache.log4j.RollingFileAppender. [org.springframework.beans.factory.xml.XmlBea

Spring MVC+Mybatis+Maven+Velocity+Mysql 连不上数据库

问题描述 Spring MVC+Mybatis+Maven+Velocity+Mysql 连不上数据库 我的mysql没有设置密码 本地数据库可以 直接登上去的 项目里面就是连不上说密码错误 是什么原因 解决方案 解决方案二: 别的密码也试过了 反正都是本地用nativecat可以登上去 项目里面运行的时候一直都是密码错误 解决方案三: Spring MVC+Mybatis+Maven+Velocity+Mysql 解决方案四: jia qun 482547245

新手求问,关于spring MVC+mybatis 的数据查询。。。

问题描述 新手求问,关于spring MVC+mybatis 的数据查询... 解决方案 select count(1),type from table group by type 解决方案二: 这个和springmvc以及mybatis没有关系,,只是一个逻辑的问题而已,查询后按不同的name统计不就可以了吗