【SSM进阶学习系列丨整合篇】Spring+SpringMVC+MyBatis 框架配置详解

在这里插入图片描述

文章目录

  • 一、环境准备
    • 1.1、创建数据库和表
    • 1.2、导入框架依赖的jar包
    • 1.3、修改Maven的编译版本
    • 1.4、完善Maven目录
    • 1.5、编写项目需要的包
    • 1.6、编写实体、Mapper、Service
  • 二、配置MyBatis环境
    • 2.1、配置mybatis的主配置文件
    • 2.2、编写映射文件
    • 2.3、测试环境是否正确
  • 三、配置Spring环境
    • 3.1、编写主配置文件
    • 3.2、测试Spring环境是否正确
  • 四、Spring整合MyBaits框架
    • 4.1、定义数据库配置
    • 4.2、主配置文件中引入properties配置文件
    • 4.3、注册数据源
    • 4.4、定义事务管理器
    • 4.5、开启事务的注解驱动支持
    • 4.6、配置SqlSessionFactoryBean
    • 4.7、配置自动扫描所有 Mapper 接口和文件
    • 4.8、测试
  • 五、配置SpringMVC环境
    • 5.1、主配置文件
    • 5.2、web.xml配置前端控制器
  • 六、Spring集成SpringMVC环境

在这里插入图片描述

一、环境准备

1.1、创建数据库和表

create database ssm;

use ssm;

create table t_account(
	id int primary key auto_increment,
  	name varchar(30),
  	age int,
  	balance int
);

insert into t_account values(default,'HelloWorld',23,100);

1.2、导入框架依赖的jar包

​ 由于我们整合的是SpringMVC、Spring和MyBatis,所以需要将这三个框架所需要的jar包导入到项目中。注意:由于要连接数据库,所以仍需要数据库驱动包。

注意:MyBatis框架和Spring框架整合需要一个mybatis-spring的jar包,该jar包的作用是两个框架的转换包。

<dependencies>
   <!--  MyBatis框架核心jar包  -->
   <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis</artifactId>
       <version>3.5.3</version>
   </dependency>

   <!-- MySQL数据库驱动包 -->
   <dependency>
      	<groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
   </dependency>
  
  	<!-- 导入Spring的jar包-->
    <dependency>
       	<groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.1.RELEASE</version>
    </dependency>

    <!-- 添加对AOP的支持  -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>

    <!-- 事务的jar包    -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.2.1.RELEASE</version>
    </dependency>
  
   	<!-- 操作数据库的支持	-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.1.RELEASE</version>
    </dependency>
  
  	<!--包含web应用开发时,用到spring框架时所需的核心类、文件上传以及工具类等-->
  	<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.1.RELEASE</version>
    </dependency>

    <!--与SpringMVC框架相关的jar包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.1.RELEASE</version>
    </dependency>
  	
  	<!--与json相关的jar包-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.5</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.5</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.5</version>
    </dependency>
  
  	<!--原生的servlet的jar包-->
    <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</version>
          <scope>provided</scope>
    </dependency>
  
  	<!-- JSTL表达式 -->
  	<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
  
  	<!--文件上传的jar包-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
  	</dependency>
	
  	 <!--  log4j日志包  -->
     <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
     </dependency>
  
  	<!-- spring的测试包-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.2.1.RELEASE</version>
        <scope>test</scope>
    </dependency>
  
  	<!--  单元测试框架  -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
  
	<!-- MyBatis框架和Spring框架转换的转换包-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.3</version>
    </dependency>
  
  	<!-- 阿里巴巴的数据源 -->
  	<dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.21</version>
    </dependency>
</dependencies>

1.3、修改Maven的编译版本

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

1.4、完善Maven目录

在这里插入图片描述

1.5、编写项目需要的包

cn.bdqn.domain
cn.bdqn.mapper
cn.bdqn.service
cn.bdqn.controller
cn.bdqn.utils
cn.bdqn.exception

1.6、编写实体、Mapper、Service

public class Account {        
                              
    private int id;           
                              
    private String name;      
                              
    private Integer age;      
                              
    private Integer balance; 

	// 生成get和set方法、toString方法
}
public interface AccountMapper {
    
    // 查询所有的账号
    public List<Account> selectAll();
 
    // 保存账号
    public void insert(Account account);
}
public interface AccountService {

    // 查询所有账号
    public List<Account> queryAll();

    // 保存账号
    public void save(Account account);
}
public class AccountServiceImpl implements AccountService {

    // 查询全部账号
    public List<Account> queryAll() {

        System.out.println("查询全部账号");
        return null;
    }

    // 保存账号
    public void save(Account account) {
        System.out.println("保存账号");
    }
}

二、配置MyBatis环境

2.1、配置mybatis的主配置文件

​ 主配置文件:mybaits-config.xml.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的主配置文件 -->
<configuration>
    <typeAliases>
        <!-- 批量起别名  -->
        <package name="cn.bdqn.domain"/>
    </typeAliases>

    <!-- 配置环境 -->
    <environments default="mysql">
        <!-- 配置mysql的环境-->
        <environment id="mysql">
            <!-- 配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源(连接池) -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///ssm?allowMultiQueries=true"/>
                <property name="username" value="root"/>
                <property name="password" value="1234567"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="cn.bdqn.mapper"/>
    </mappers>

</configuration>

2.2、编写映射文件

​ 在resources目录下新建与mapper接口同名的目录。即:cn/bdqn/mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.bdqn.mapper.AccountMapper">

    <!-- 查询全部账号信息-->
    <select id="selectAll" resultType="cn.bdqn.domain.Account">
        select
            id,name,age,balance
        from
            t_account
    </select>
    
    <!--  新增账号  -->
    <insert id="insert">
        insert into t_account(name,age,balance) values (#{name},#{age},#{balance})
    </insert>
    
</mapper>

2.3、测试环境是否正确

    @Test
    public void testMyBatis() throws Exception{
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");

        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);

        SqlSession session = ssf.openSession();

        AccountMapper accountMapper = session.getMapper(AccountMapper.class);
        List<Account> accounts = accountMapper.selectAll();
        System.out.println(accounts);

        is.close();
        session.close();
    }

三、配置Spring环境

3.1、编写主配置文件

注意:由于是SSM项目整合,在Spring主配置文件中配置扫描包的时候仅仅针对Service业务层、Mapper持久化层等注解的扫描,对于Web层,交由SpringMVC框架去处理。

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
		
 	    <!-- 1、配置扫描包,排除Controller层的注解	-->
    <context:component-scan base-package="cn.bdqn">
        <context:exclude-filter	type="annotation" 																			expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

3.2、测试Spring环境是否正确

    @Test
    public void testSpring() throws Exception{

        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

        AccountService accountService = (AccountService) ac.getBean("accountService");

        System.out.println(accountService);
    }

四、Spring整合MyBaits框架

​ 注意:我们在配置MyBaits环境的时候,数据源配置在了MyBatis上,现在由于Spring整合MyBaits,则对于在MyBatis中配置的数据源要交给Spring去管理。在这里,我们用的阿里巴巴的数据源。

​ 官网

4.1、定义数据库配置

​ 定义db.properties数据库配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssm?allowMultiQueries=true
jdbc.username=root
jdbc.password=1234567

4.2、主配置文件中引入properties配置文件

<context:property-placeholder location="classpath:db.properties"/>

4.3、注册数据源

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" 
      init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
</bean>

4.4、定义事务管理器

<bean id="transactionManager" 																	  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

4.5、开启事务的注解驱动支持

<tx:annotation-driven transaction-manager="transactionManager"/>

4.6、配置SqlSessionFactoryBean

<!--作用:创建SqlSessionFactory工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  	<property name="dataSource" ref="dataSource" />
</bean>

4.7、配置自动扫描所有 Mapper 接口和文件

<!-- 作用:能够扫描所有的Mapper接口的实现,让这些Mapper能够自动注入-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.bdqn.mapper"/>
</bean>

4.8、测试

    @Test
    public void testSpringAndMyBatis() throws Exception{
        ApplicationContext ac =  new ClassPathXmlApplicationContext("beans.xml");

        AccountService accountService = (AccountService) ac.getBean("accountService");

        List<Account> accounts = accountService.queryAll();

        System.out.println(accounts);
    }

五、配置SpringMVC环境

5.1、主配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mv="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置扫描包  -->
    <context:component-scan base-package="cn.bdqn" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 配置视图解析器,作用是配置目录前缀和文件后缀,然后解析为一个资源文件 -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <mvc:annotation-driven/>
</beans>

5.2、web.xml配置前端控制器

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

  <servlet>
    <servlet-name>frontDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:SpringMVC.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>frontDispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

六、Spring集成SpringMVC环境

​ 在web.xml文件中配置。

<!--	配置 spring 提供的监听器,用于启动服务时加载容器 。	-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 手动指定 spring 配置文件位置 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:beans.xml</param-value>
</context-param>

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/575536.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

streamlit data_editor学习之 LLM理论内存占用量计算器

streamlit data_editor学习之 LLM理论内存占用量计算器 一.效果二.代码三.运行命令四.参考链接 根据用户设置的LLM参数,计算设备内存的占用量。以web的形式方便共享,可以插入多条记录,表格更新后,可以动态计算结果 一.效果 二.代码 import streamlit as st #1.31.1 import cv…

【八股】Spring Boot

SpringBoot是如何实现自动装配的&#xff1f; 首先&#xff0c;SpringBoot的核心注解SpringBootApplication里面包含了三个注解&#xff0c;SpringBootConfigurationEnableAutoConfigurationComponentScan&#xff0c;其中EnableAutoConfiguration是实现自动装配的注解&#x…

如何最大程度使用AWS?

随着云计算技术的不断发展&#xff0c;AWS已经成为众多企业的首选&#xff0c;为其提供了强大的基础设施和服务。那么如何最大程度地、灵活地利用AWS&#xff0c;成为许多企业专注的焦点。九河云作为AWS的合作伙伴&#xff0c;为读者们提供一些技巧和策略&#xff0c;帮助读者充…

UL认证防逆流多功能监测装置AGF-AE-D

安科瑞薛瑶瑶18701709087/17343930412 在单逆变器系统中&#xff0c;仪表直接与逆变器相连。如果您的变频器有一个内置的收入等级表&#xff08;RGM&#xff1b;该变频器 被称为收入等级变频器&#xff09;&#xff0c;您可以在 RGM 的同一总线上连接一个外部仪表。

【React】Sigma.js框架网络图-入门篇(2)

通过《【React】Sigma.js框架网络图-入门篇》有了基本认识 由于上一篇直接给出了基本代码示例&#xff0c;可能看着比较复杂也不知道是啥意思&#xff1b; 今天从理论入手重新认识下&#xff01; 一、基本认识 首先&#xff0c;我们先了解下基础术语&#xff1a; 图(Graph)&…

波高仪:数字浪高仪解析

波高仪&#xff0c;也被称为数字浪高仪&#xff0c;是一种专门用于测量波浪高度的设备。它采用低功耗微处理器、24bit高精度AD转换器和长距离通信技术&#xff0c;配备电容式波高传感器&#xff0c;具有线性好、功耗低、量精度高、传输距离远、性能稳定、抗干扰能力强等特点。 …

vue中使用echarts实现X轴动态时间(天)的折线图表

项目要求x轴以一天为间隔&#xff0c;时间是动态返回的数据&#xff0c;折线图平滑展示 实现代码如下&#xff1a; <div class"echarts-main"><v-chart ref"echarts" :options"options" /> </div>// 局部引入vue-echarts im…

Python实现线性拟合及绘图

Python实现线性拟合及绘图 当时的数字地形实验&#xff0c;使用matplotlib库绘制了一张图表表示不同地形类别在不同分辨率下的RMSE值&#xff0c;并分别拟合了一条趋势线。现在来看不足就是地形较多时&#xff0c;需要使用循环更好一点&#xff0c;不然太冗余了。 代码逻辑 …

【讯为Linux驱动笔记1】申请一个字符设备

Linux下每个设备都需要有一个专属设备号&#xff1a;主设备号 次设备号 【申请字符设备】 主设备号&#xff1a;一类驱动&#xff1a;如&#xff1a;USB驱动 次设备号&#xff1a;这类驱动下的某个设备 如&#xff1a;键盘鼠标 设备号是32位的dev_t类型的&#xff0c;高12位主…

Python对Excel两列数据进行运算

&#x1f47d;发现宝藏 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。【点击进入巨牛的人工智能学习网站】。 Python对Excel两列数据进行运算 在日常工作中&#xff0c;经常会遇到需要对Excel表格中的数…

Scala 04 —— Scala Puzzle 拓展

Scala 04 —— Scala Puzzle 拓展 文章目录 Scala 04 —— Scala Puzzle 拓展一、占位符二、模式匹配的变量和常量模式三、继承 成员声明的位置结果初始化顺序分析BMember 类BConstructor 类 四、缺省初始值与重载五、Scala的集合操作和集合类型保持一致性第一部分代码解释第二…

Python 数据可视化 boxplot

Python 数据可视化 boxplot import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns# 读取 TSV 文件 df pd.read_csv(result.tsv, sep\t)normal_df df[df["sample_name"].str.contains("normal")] tumor_df df…

【Git教程】(十五)二分法排错 — 概述及使用要求,执行过程及其实现(用二分法人工排错或自动排错),替代解决方案 ~

Git教程 二分法排错 1️⃣ 概述2️⃣ 使用要求3️⃣ 执行过程及其实现3.1 用二分法人工排错3.2 用二分法自动排错 4️⃣ 替代解决方案 在开发过程中&#xff0c;我们经常会突然遇到一个错误&#xff0c;是之前早期版本在成功通过测试时没有出现过的。这时候&#xff0c;时下较…

基于实现地图弹窗轮播功能及遇到的问题解决

基本使用 获取地图 geojson 数据 链接&#xff1a; 阿里云数据可视化平台 获取ECharts npm install echarts 或者是使用地址链接 <script src"https://registry.npmmirror.com/echarts/5.4.3/files/dist/echarts.min.js"></script> <script src…

关于螺栓的注意事项和正确操作方法——SunTorque智能扭矩系统

智能扭矩系统-智能拧紧系统-扭矩自动控制系统-SunTorque 螺栓&#xff0c;作为一种常见的紧固件&#xff0c;广泛应用于各种机械设备和结构中。在日常生活和工作中&#xff0c;我们经常需要接触到螺栓&#xff0c;因此了解螺栓的一些注意事项和正确操作方法对于确保设备的安全…

【C#】Stopwatch计时器

使用Stopwatch检查C#中代码块的执行时间&#xff0c;比如歌曲&#xff0c;图片的下载时间问题 首先&#xff0c;我们可看到Stopwatch 类内部的函数。 根据需求&#xff0c;我们具体可使用到 Start() 开始计时&#xff0c;Stop() 停止计时等 //创建 Stopwatch 实例 Stopwatch …

Intersection Observer API探索

我们经常遇到这样的需求——检测一个元素是否可见或者两个元素是否相交&#xff0c;如 ● 图片懒加载——当图片滚动到可见时才进行加载 ● 内容无限滚动——也就是用户滚动到接近内容底部时直接加载更多&#xff0c;而无需用户操作翻页&#xff0c;给用户一种网页可以无限滚动…

分布式密钥生成

可验证且无经销商 分布式密钥生成 (DKG) 是一种加密协议&#xff0c;使多方能够协作生成共享密钥&#xff0c;而无需任何一方完全了解密钥。 它通过在多个参与者之间分配信任来增强各种应用程序的安全性&#xff0c;从而降低密钥泄露的风险。 我们引入了一种可验证且无经销商的…

深度学习从入门到精通—Transformer

1.绪论介绍 1.1 传统的RNN网络 传统的RNN&#xff08;递归神经网络&#xff09;主要存在以下几个问题&#xff1a; 梯度消失和梯度爆炸&#xff1a;这是RNN最主要的问题。由于序列的长距离依赖&#xff0c;当错误通过层传播时&#xff0c;梯度可以变得非常小&#xff08;消失…