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

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: 原文:Spring MVC + MyBatis整合(IntelliJ IDEA环境下)一些重要的知识: mybais-spring.jar及其提供的API: SqlSessionFactoryBean: SqlSessionFactory是由SqlSessionFactoryBuilder产生的,Spring整合MyBats时SqlSessionFactoryBean也是由SqlSessionFactoryBuilder生成的。
原文: 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>

运行:

 

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
5天前
|
安全 Java 数据库连接
在IntelliJ IDEA中通过Spring Boot集成达梦数据库:从入门到精通
在IntelliJ IDEA中通过Spring Boot集成达梦数据库:从入门到精通
|
5天前
|
前端开发 Java 应用服务中间件
Spring MVC框架概述
Spring MVC 是一个基于Java的轻量级Web框架,采用MVC设计模型实现请求驱动的松耦合应用开发。框架包括DispatcherServlet、HandlerMapping、Handler、HandlerAdapter、ViewResolver核心组件。DispatcherServlet协调这些组件处理HTTP请求和响应,Controller处理业务逻辑,Model封装数据,View负责渲染。通过注解@Controller、@RequestMapping等简化开发,支持RESTful请求。Spring MVC具有清晰的角色分配、Spring框架集成、多种视图技术支持以及异常处理等优点。
12 1
|
13天前
|
Web App开发 缓存 Java
IDEA环境下的热加载与热部署
本文探讨了开发中自动更新代码以提高效率的方法,提到了“热启动”等不同术语,并指出其实现比命名更重要。介绍了两种方式:使用Jrebel插件(需付费,可能与某些Spring Boot版本不兼容)和Spring Boot的devtools热加载。devtools通过两个ClassLoader实现快速更新,只需添加依赖并配置IDEA。此外,建议配合LiveReload浏览器插件自动刷新页面。遇到问题可能与JDK版本不匹配或缓存有关。
|
21天前
|
Go 开发工具 开发者
Intellij IDEA 配置 Go 语言开发环境
【4月更文挑战第14天】本篇文章 Huazie 向大家介绍使用 Intellij IDEA 搭建 Go 语言开发环境,并演示编译运行Go语言代码
32 1
Intellij IDEA 配置 Go 语言开发环境
|
25天前
|
Java Windows Spring
Spring Boot 3.x 全新的热部署配置方式(IntelliJ IDEA 2023.1)
Spring Boot 3.x 全新的热部署配置方式(IntelliJ IDEA 2023.1)
29 1
|
1月前
|
数据采集 前端开发 Java
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
23 3
|
1月前
|
存储 前端开发 Java
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
14 1
|
1月前
|
前端开发 Java Spring
数据之桥:深入Spring MVC中传递数据给视图的实用指南
数据之桥:深入Spring MVC中传递数据给视图的实用指南
33 3
|
1月前
|
前端开发 Java 容器
家族传承:Spring MVC中父子容器的搭建与管理指南
家族传承:Spring MVC中父子容器的搭建与管理指南
26 3
|
1月前
|
前端开发 Java API
头头是道:揭示Spring MVC如何获取和处理请求头数据
头头是道:揭示Spring MVC如何获取和处理请求头数据
26 1