SSM myBatis 配置及自动生成Bean 和 Dao

2023-10-27

      因为我发现在做SSM 的配置的时候 ,配置中出现一点问题都会导致项目打包失败或者其他问题,但是我发现网上很多都没有贴出每个配置文件的代码,如果是新手在配置上就会走很多的弯路,所以这里我贴出所有配置文件的代码,这样会方便很多新手快速的构建正确的SSM项目。

       在新建Spring项目时,会自动生成这些配置文件:applicationContext.xml,web目录下面生成web.xml,dispatcher-servlet.xml

1. applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">


     <!--扫描controller(controller层注入) -->
    <context:component-scan base-package="test">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- Spring的配置文件,这里主要配置和业务逻辑有关的 -->
    <!--=================== 数据源,事务控制,xxx ================-->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="dataSource" ref="pooledDataSource"></property>
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>

    <!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描所有的dao接口的实现,加入到ioc容器中 -->
        <property name="basePackage" value="test.dao"></property>
    </bean>


    <!-- 配置一个可以执行批量的sqlSession  批量数据库操作-->
    <bean id="sqlSession"  class="org.mybatis.spring.SqlSessionTemplate" >
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory">
        </constructor-arg>
        <constructor-arg name="executorType" value="BATCH"></constructor-arg>

    </bean>

    <!-- ================================================= -->


    <!-- ======================事务控制的配置 ========================-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 控制数据源 -->
        <property name="dataSource" ref="pooledDataSource"></property>
    </bean>

    <!-- 开启基于注解的事务,使用xml配置形式的事务(必要主要的都是使用配置) -->
    <aop:config>
        <!-- 切入点表达式 -->
        <aop:pointcut expression="execution(* test.service..*(..))" id="txPoint"/>
        <!-- 配置事务增强  指明切入点-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>

    <!--配置事务增强 ,事务如何切入-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 所有方法都是事务方法 -->
            <tx:method name="*"/>
            <!-- 以get开始的所有方法 -->
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>

   
</beans>

2. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">
    <!--1、启动Spring的容器  -->
    <!-- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- springMVC核心配置 -->
    <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--<init-param>-->
            <!--<param-name>contextConfigLocation</param-name>-->
            <!--<param-value>classpath:.xml</param-value>-->
        <!--</init-param>-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!-- 错误跳转页面 -->
    <error-page>
        <!-- 路径不正确 -->
        <error-code>404</error-code>
        <location>/WEB-INF/errorpage/404.jsp</location>
    </error-page>
    <error-page>
        <!-- 没有访问权限,访问被禁止 -->
        <error-code>405</error-code>
        <location>/WEB-INF/errorpage/405.jsp</location>
    </error-page>
    <error-page>
        <!-- 内部错误 -->
        <error-code>500</error-code>
        <location>/WEB-INF/errorpage/500.jsp</location>
    </error-page>

</web-app>

3.dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    <!-- SpringMvc的配置文件,包含网站跳转文件的配置 -->

    <context:component-scan base-package="test" use-default-filters="false">
        <!-- -只扫描控制器 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- ,配置视图解析器 如何把 handler 方法返回值解析为实际的物理视图,jsp路径的前缀和后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 两个标准配置 -->
    <!-- 将springmvc不能处理的请求交给tomcat -->
    <mvc:default-servlet-handler/>
    <!-- 能支持springmvc更高级的一些功能,JRS303校验,ajax请求..映射动态请求 -->
    <mvc:annotation-driven></mvc:annotation-driven>

</beans>


mybatis 自动生成代码需要 

1.mybatis-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">
 <configuration>
 	 <settings>
 		<setting name="mapUnderscoreToCamelCase" value="true"/>
 	</settings> 
 	  <typeAliases>
  		<package name="test.bean"/>
 	</typeAliases>

 	
 	<!--<!– 引入分页插件 –>-->
 	 	<!--<plugins >-->
 	 	<!--<plugin interceptor="com.github.pagehelper.PageInterceptor">-->
 	 	<!--<!– 分页参数合理化 –>-->
 	 	<!--<property name="reasonable" value="true"/>-->
		<!--</plugin>-->
 	 	<!--</plugins>-->
 </configuration>  

2 . mbg.xml(自动生成代码的关键文件)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

  <context id="DB2Tables" targetRuntime="MyBatis3">
  
	  <commentGenerator>
	  <property name="suppressAllComments" value="true" />
	</commentGenerator>
  
  
  <!-- 配置数据库连接 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                    connectionURL="jdbc:mysql://localhost:3306/test"
                    userId="root"
                    password="">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

 
   <!-- 指定javabean生成的位置 -->
    <javaModelGenerator targetPackage= "test.bean"
    targetProject="src/main/java">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>



	<!-- 指定sql映射文件的生成位置  -->
    <sqlMapGenerator targetPackage="mapper"
    targetProject="src/main/resources">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>


  <!-- 指定dao接口生成的位置,mapper接口 -->
    <javaClientGenerator type="XMLMAPPER" 
    targetPackage="test.dao"
    targetProject="src/main/java" >
    
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>


 	<!-- 指定每个表的生成策略  -->
    <table tableName="user" domainObjectName="User">
    </table>

  </context>
   
</generatorConfiguration>

并将该文件和mybatis-generator-core-1.3.5.jar   mysql-connector-java-5.1.29.jar 这两个库放在一个目录下面,再terminal或者命令窗口下定位到该目录后输入命令:

  java -cp mybatis-generator-core-1.3.5.jar:mysql-connector-java-5.1.29.jar org.mybatis.generator.api.ShellRunner -configfile mbg.xml -overwrite

命令执行成功后就会在你制定的目录生成 对应的 *mapper.xml , bean,dao接口

这就是基本的配置,在理解配置文件中每一项功能后就可以进行扩展。


补充:建表可以利用* .xml的sql文件

/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50550
Source Host           : localhost:3306
Source Database       : ssm_crud

Target Server Type    : MYSQL
Target Server Version : 50550
File Encoding         : 65001

Date: 2017-07-16 02:43:12
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `tbl_emp`
-- ----------------------------
DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `device_num` varchar(255) NOT NULL,
  `create_time` varchar(255) NOT NULL,
  `last_time` varchar(255) DEFAULT NULL,
  `nickname` varchar(255) DEFAULT NULL,
  `device_type` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1018 DEFAULT CHARSET=utf8;

-- -----------

-- ----------------------------
-- Table structure for `tnl_dept`
-- ----------------------------
DROP TABLE IF EXISTS `tnl_dept`;
CREATE TABLE `tnl_dept` (
  `dept_id` int(11) NOT NULL AUTO_INCREMENT,
  `dept_name` varchar(255) NOT NULL,
  PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tnl_dept
-- ----------------------------
INSERT INTO `tnl_dept` VALUES ('1', '开发部');
INSERT INTO `tnl_dept` VALUES ('2', '测试部');

然后在 mysql 下 执行 例:

mysql> use test; //设置当前要导入数据的dbtest数据库
mysql> source D:\db.sql; //导入数据 

就可以执行文件中的SQL 语句了。


我会上传我配置好的一个 最基本的项目,新手可以用来测试学习扩展,后面会继续跟进SSM 方面的扩展

项目下载地址:点击打开链接



本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SSM myBatis 配置及自动生成Bean 和 Dao 的相关文章

  • 蓝桥杯零基础冲过赛-第22天

    注意 因为蓝桥杯大部分题目都会涉及到数据规模过大问题 所以大整数是解决数据规模过大的问题的其中一种最简便的方式 核心 竖式个位对齐原理 文章目录 大整数加法 大整数减法 大整数乘法 大整数除法 大整数余数 大整数加法 意义 因为数据类型有s
  • 摸鱼时间少? 是时候学会用Vue自定义指令进行业务开发了

    文章目录 前言 一 博主用Vue自定义指令在业务中实现了什么需求 1 首屏Loading切换指令 用来占位 支持调节Loading样式 2 复制指令 3 文件流形式下载后端数据 转blob下载 4 防抖 支持设置延迟时间 5 按钮或菜单权限

随机推荐

  • 永远怀念左耳朵耗子陈皓——IT界的失去

    2023年 中国IT界遭遇了一次巨大的损失 左耳朵耗子陈皓先生的离世让人震惊和悲伤 作为一位杰出的技术专家和开源倡导者 他为IT界做出了卓越贡献 本文将回顾他的职业生涯和他对IT界的重要影响 以及他离世后的深远意义 第一部分 IT界的璀璨明
  • Opencv

    Opencv 检测框线 模糊判断 计算图片相似度 开操作检测横竖线 拉普拉斯方差判断模糊度 直方图统计判断图片相似性 开操作检测横竖线 开操作是先选定合适结构元对图像进行腐蚀处理再用相同结构元对图像进行膨胀处理 开操作可以平滑物体轮廓 断开
  • C++并发编程(5):std::unique_lock、互斥量所有权传递、锁的粒度

    std unique lock lt gt 灵活加锁 参考博客 线程间共享数据 使用互斥量保护共享数据 C 多线程unique lock详解 多线程编程 五 unique lock 相较于std lock guard std unqiue
  • iOS - 线程中常见的几种锁

    线程锁主要是用来解决 共享资源 的问题 实际开发中或多或少的都会用到各类线程锁 为了线程的安全我们有必要了解常见的几种锁 下面是本人查看一些大牛的博客然后整理的内容 加上自己的一些见解 水平有限 如果不慎有误 欢迎交流指正 常见锁列举 自旋
  • OpenStack 学习笔记(一) 概况

    偶然机会 需要了解一下OpenStack的概况 因此与几个同事一起看了一下 此学习笔记是记录一下学习的知识点 备自己以后回顾复习 一 OpenStack 概况 OpenStack是一个由NASA 美国国家航空航天局 和Rackspace合作
  • python处理wav文件时出现error:X和Y不在同一维度

    python处理wav文件时出现error X和Y不在同一维度 ValueError x and y must have same first dimension but have shapes 1290240 and 2580480 记录
  • Python 动态规划解决不同路径问题

    目录 一 LeetCode 62 不同路径 1 题目描述 2 解题思路 3 代码 二 LeetCode 63 不同路径II 1 题目描述 2 解题思路 3 代码 三 LeetCode 64 最小路径和 1 题目描述 2 解题思路 3 代码
  • 初识Django

    虚拟环境 python pip install Virtualenv pip install Virtualenvwrapper win workon 查看当前虚拟环境 mkvirtualenv xx 创建虚拟环境xx 默认的虚拟环境存放的
  • 编译系统总结篇-Android10.0编译系统(十一)

    Android取经之路 的源码都基于Android Q 10 0 进行分析 Android取经之路 系列文章 系统启动篇 Android系统架构Android是怎么启动的Android 10 0系统启动之init进程Android10 0系
  • Linux CentOS7 添加中文输入法

    在安装CentOS7时 现在默认安装了桌面中文系统 可以切换为英文 中英文可以按要求随时更换 而在CentOS7桌面环境下 显示中文非常方便 正确 但不能录入中文 在远程登录系统的情况下 不论是系统语言 LANG 设置为中文或英文 都可以在
  • 获取lib库中Filler/buffer/CK单元的类型——innovus

    1 Filler的所有类型 命令 dbGet dbGet head allCells name FIL p name 2 BUFFER的所有类型 命令 dbGet dbGet head allCells name BUF p name 3
  • 实时时钟芯片DS1302

    一 DS1302主要介绍 1 DS1302 的特点 DS1302 是 DALLAS 达拉斯 公司推出的一款涓流充电时钟芯片 DS1302 实时时钟芯片广泛应用于电话 传真 便携式仪器等产品领域 它的主要性能 指标如下 1 DS1302 是一
  • 正则校验-我需要的正则表达式知识

    正则校验 我需要的正则表达式知识 正则表达式由正则表达式引擎提供支持 不同编程环境有不同的正则表达式引擎 在实际使用正则表达式的过程中会有一些差别 什么是正则表达式 正则表达式是用于描述匹配复杂字符串规则的工具 一个正则表达式对应着一个文本
  • Mybatis基础知识浅谈

    Mybatis浅谈 目录 1 什么是Mybatis 2 Mybatis的快速入门 2 1MyBatis开发步骤 2 2 环境搭建 3 MyBatis的增删改查操作 3 1 MyBatis的插入数据操作 3 2 MyBatis的修改数据操作
  • 可执行文件的格式(ELF格式)详解

    各种讲解elf文件格式一上来就是各种数据类型 看了半天却不知道这些数据类型是干啥的 所以咱就先找个例子直接上手 这样对elf文件格式有个具体而生动的了解 然后再去看那些手册 就完全不惧了 我们使用一个汇编程序max s并对其进行编译链接产生
  • vant 使用deep修改样式不好使解决方案

  • php7 libevent扩展,PHP7 安装event扩展的实现方法

    Libevent 是一个用C语言编写的 轻量级的开源高性能I O框架 支持多种 I O 多路复用技术 epoll poll dev poll select 和 kqueue 等 支持 I O 定时器和信号等事件 注册事件优先级 PHP提供了
  • 【牛客】四选一多路器

    描述 制作一个四选一的多路选择器 要求输出定义上为线网类型 状态转换 d0 11 d1 10 d2 01 d3 00 信号示意图 波形示意图 输入描述 输入信号 d1 d2 d3 d4 sel 类型 wire 输出描述 输出信号 mux o
  • 前端面试题之React

    文章目录 1 React生命周期 V16 3 之前 挂载阶段 组件更新阶段 卸载阶段 新增后 挂载阶段 更新阶段 static getDerivedStateFromProps shouldComponentUpdate render ge
  • SSM myBatis 配置及自动生成Bean 和 Dao

    因为我发现在做SSM 的配置的时候 配置中出现一点问题都会导致项目打包失败或者其他问题 但是我发现网上很多都没有贴出每个配置文件的代码 如果是新手在配置上就会走很多的弯路 所以这里我贴出所有配置文件的代码 这样会方便很多新手快速的构建正确的