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

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用系列 2核4GB
简介: 原文: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>

运行:

 

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
3月前
|
XML Java 数据格式
使用idea中的Live Templates自定义自动生成Spring所需的XML配置文件格式
本文介绍了在使用Spring框架时,如何通过创建`applicationContext.xml`配置文件来管理对象。首先,在resources目录下新建XML配置文件,并通过IDEA自动生成部分配置。为完善配置,特别是添加AOP支持,可以通过IDEA的Live Templates功能自定义XML模板。具体步骤包括:连续按两次Shift搜索Live Templates,配置模板内容,输入特定前缀(如spring)并按Tab键即可快速生成完整的Spring配置文件。这样可以大大提高开发效率,减少重复工作。
使用idea中的Live Templates自定义自动生成Spring所需的XML配置文件格式
|
6月前
|
Cloud Native Java 对象存储
面向未来的架构设计:Spring Cloud和Netflix OSS在云原生环境下的发展趋势
展望未来,随着5G、边缘计算等新技术的兴起,微服务架构的设计理念将会更加深入人心,Spring Cloud和Netflix OSS也将继续引领技术潮流,为企业带来更为高效、灵活且强大的解决方案。无论是对于初创公司还是大型企业而言,掌握这些前沿技术都将是在激烈市场竞争中脱颖而出的关键所在。
107 0
|
3月前
|
Java Spring
【Spring配置】idea编码格式导致注解汉字无法保存
问题一:对于同一个项目,我们在使用idea的过程中,使用汉字注解完后,再打开该项目,汉字变成乱码问题二:本来a项目中,汉字注解调试好了,没有乱码了,但是创建出来的新的项目,写的注解又成乱码了。
|
3月前
|
前端开发 Java 开发者
这款免费 IDEA 插件让你开发 Spring 程序更简单
Feign-Helper 是一款支持 Spring 框架的 IDEA 免费插件,提供 URL 快速搜索、Spring Web Controller 路径一键复制及 Feign 与 Controller 接口互相导航等功能,极大提升了开发效率。
|
4月前
|
存储 运维 安全
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
通过以上措施,可以保证Spring Boot项目的配置管理在专业水准上,并且易于维护和管理,符合搜索引擎收录标准。
106 2
|
5月前
|
搜索推荐 Java 数据库连接
Java|在 IDEA 里自动生成 MyBatis 模板代码
基于 MyBatis 开发的项目,新增数据库表以后,总是需要编写对应的 Entity、Mapper 和 Service 等等 Class 的代码,这些都是重复的工作,我们可以想一些办法来自动生成这些代码。
72 6
|
5月前
|
Java 应用服务中间件 Maven
idea+maven+tomcat+spring 创建一个jsp项目
这篇文章介绍了如何在IntelliJ IDEA中使用Maven和Tomcat创建一个JSP项目,包括配置Maven依赖、设置Tomcat服务器、编写JSP页面、创建控制器和配置文件,以及项目的运行结果。
318 0
idea+maven+tomcat+spring 创建一个jsp项目
|
5月前
|
Cloud Native Java 对象存储
面向未来的架构设计:Spring Cloud和Netflix OSS在云原生环境下的发展趋势
面向未来的架构设计:Spring Cloud和Netflix OSS在云原生环境下的发展趋势
82 1
|
5月前
|
Java 关系型数据库 开发工具
idea创建不了spring2.X版本,无法使用JDK8,最低支持JDK17 , 如何用idea创建spring2.X版本,使用JDK8解决方案
本文提供了解决方案,如何在IDEA中创建Spring 2.X版本的项目并使用JDK8,尽管Spring 2.X已停止维护且IDEA不再直接支持,通过修改pom.xml或使用阿里云的国内源来创建项目。
261 0
idea创建不了spring2.X版本,无法使用JDK8,最低支持JDK17 , 如何用idea创建spring2.X版本,使用JDK8解决方案
|
6月前
|
Java 应用服务中间件 Spring
IDEA 工具 启动 spring boot 的 main 方法报错。已解决
IDEA 工具 启动 spring boot 的 main 方法报错。已解决
119 4