配置文件

本文详细介绍了如何整合Spring、SpringMVC和MyBatis(SSM),包括数据库配置、生成实体类、配置Spring及SpringMVC等内容。

schema.sql

drop database if exists ssm_crud ;
create database ssm_crud default character set utf8;
use ssm_crud;

drop table if exists t_emp;
drop table if exists t_dept;

-- 员工表
create table t_emp(
  id bigint auto_increment,
  name varchar(255) not null unique comment'员工姓名',
  gender char(1) not null comment'性别 M 男 F 女',
  email varchar(255) not null comment'邮箱',
  dept_id bigint comment'部门id',
  primary key(id)
)ENGINE=InnoDB;

alter table t_emp comment '员工表';

-- 部门表
create table t_dept(
  id bigint auto_increment,
  name varchar(255) not null unique comment'部门名称',
  primary key(id)
);

alter table t_dept comment '部门表';

data.sql

insert into t_dept(name)values('开发部');
insert into t_dept(name)values('测试部');

insert into t_emp(name,gender,email,dept_id)values('tom','1','tom@qq.com',1);
insert into t_emp(name,gender,email,dept_id)values('kyo','2','kyo@qq.com',2);

select * from t_dept;
select * from t_emp;

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" defaultModelType="flat">

        <commentGenerator>
            <!-- 是否取消注释 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!-- 配置数据库连接 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/ssm_crud"
                        userId="root"
                        password="root">
        </jdbcConnection>

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

        <!-- 指定javaBean生成的位置 -->
        <javaModelGenerator targetPackage="org.yun.ssm.model"
                            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="org.yun.ssm.dao"
                             targetProject="src\main\java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>


        <!-- table指定每个表的生成策略 -->
        <table tableName="t_emp" domainObjectName="Emp"/>
        <table tableName="t_dept" domainObjectName="Dept"/>
    </context>
</generatorConfiguration>

在如下目录下建立MBGTest.java

代码:

public class MBGTest {
    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<>();
        boolean overwrite = true;
        File configFile = new File("mbg.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
        System.out.println("success...");
    }
}

直接运行main()方法,即可生成MyBatis所需的文件。

jdbc.properties

#数据库链接信息
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_crud
jdbc.username=root
jdbc.password=root

log4j.properties

# Output pattern : date [thread] priority category - message
log4j.rootLogger=INFO, Console, RollingFile

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

#RollingFile
#log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.RollingFile.File=logs/ssm_crud.log
#log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
#log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

#print log
#log4j.logger.org.yun.ssm.dao=TRACE
#log4j.logger.org.yun.ssm.web=TRACE
log4j.logger.org.yun.ssm=TRACE

spring.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.xsd
	   http://www.springframework.org/schema/beans
	   http://www.springframework.org/schema/beans/spring-beans.xsd
	   http://www.springframework.org/schema/tx
	   http://www.springframework.org/schema/tx/spring-tx.xsd
	   http://www.springframework.org/schema/context
	   http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="org.yun.ssm">
        <!--排除org.yun.ssm包下的@Controller-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--指定xxxMapper.xml文件的位置-->
        <property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/>
        <!--指定实体类类型别名所在包的位置-->
        <property name="typeAliasesPackage" value="org.yun.ssm.model"/>
        <!--mybatis的相关配置-->
        <property name="configuration">
            <bean class="org.apache.ibatis.session.Configuration">
                <!--映射为驼峰命名法。例如 my_name → myName-->
                <property name="mapUnderscoreToCamelCase" value="true"/>
            </bean>
        </property>
        <property name="plugins">
            <array>
                <!--引入PageHelper分页插件-->
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            reasonable=true
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>


    <!-- 配置mybatis的dao接口扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="org.yun.ssm.dao"/>
    </bean>

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

    <!--配置声明式事务-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="*"/>
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="txPoint" expression="execution(* org.yun.ssm.service..*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>
    
</beans>

这里整合了mybatis的配置,所以不需要再编写mybatis-config.xml文件了。

spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd">


    <!--注意:use-default-filters 不能使用默认的true,而是要改为false-->
    <context:component-scan base-package="org.yun.ssm" use-default-filters="false">
        <!--只扫描org.yun.ssm包下的@Controller-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>


    <!-- 将Spring MVC 不能处理的请求交给Tomcat -->
    <mvc:default-servlet-handler/>

    <!--增加Spring MVC其他支持功能-->
    <mvc:annotation-driven/>

</beans>

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"
         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">

    <!--加载spring容器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--配置spring mvc-->
    <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:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--字符编码过滤器-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

至此,配置文件编写完毕。好多~

小结

  • schema.sql:数据表脚本。
  • data.sql:测试数据。
  • mbg.xml:mybatis-generator的配置文件。
  • jdbc.properties:数据库连接信息。
  • log4j.properties:打印SQL到控制台。
  • spring.xml:Spring配置文件。
  • spring-mvc.xml:Spring MVC配置文件。
  • web.xml:web项目配置信息。

没有mybatis-config.xml文件。 mybatis所有配置转移都到spring.xml中。

转载于:https://my.oschina.net/mondayer/blog/3033138

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值