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

      因为我发现在做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 方面的扩展

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



  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值