Spring+SpringMVC+mybatis集成的开发环境项目整合

第一步配置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_4_0.xsd"
         version="4.0">
    <!-- 指定使用 注解的方式来创建Spring容器(AnnotationConfigWebApplicationContext)  -->
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
    <!--指定标注了@Configuration的类作为配置类,多个可以用逗号分隔-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!--更换为自己包的路径-->
        <param-value>cn.yl.config.AppConfig</param-value>
    </context-param>
    <!--配置Spring的监听器:一旦web容器启动 就会根据各种配置创建Spring 的ioc容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--配置SpringMVC的servlet-->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--SpringMVC也有自己的配置文件 名字习惯叫做dispatcher-servlet.xml-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:dispatcher-servlet.xml</param-value>
        </init-param>
    </servlet>
    <!--配置映射关系-->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <!--所有的以action结尾的路径都交给 DispatcherServlet 去处理-->
        <!-- <url-pattern>*.action</url-pattern> -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--处理字符编码的过滤器-->
    <filter>
        <filter-name>Encoding</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>
    </filter>
    <filter-mapping>
        <filter-name>Encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

第二步配置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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      ">
</beans>

第三步配置dataSource.properties文件

jdbc_url=jdbc:mysql://localhost:3306/demo?useSSL=true&Unicode=true&characterEncoding=UTF-8
driverClassName=com.mysql.jdbc.Driver
jdbc_username=root
jdbc_password=admin
jdbc_initialSize=10
jdbc_maxActive=100
jdbc_minIdle=10
jdbc_maxWait=2000

第四步配置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: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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
    <!-- 指定出控制器所在的包 -->
    <context:component-scan base-package="cn.yl.controller"/>
    <!--
         视图解析器的bean
         会在控制器中转发的路径前面加上指定的前缀
    比如转发的路径是 /add 视图解析器处理后 -/WEB-INF/pages/add
        会在访问路径后面加上一个指定的后缀
        比如转发的路径是 /add 视图解析器处理后 -&ndash;&gt;/WEB-INF/pages/add.jsp
    -->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--下面两行的作用:如果是静态资源则交给web容器(tomcat)去处理,而不是 “DispactcherServlet”处理 -->
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
</beans>

第六步配置log4j.properties日志文件

# Global logging configuration ???????? debug
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

第七步配置mybatis.cfg.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="cacheEnabled" value="true"/>
    </settings>
    <!-- 为类型配置别名 -->
    <typeAliases>
        <!-- 如果这样配置 则表示该包下的所有类型的别名都是类的名称   -->
        <package name="cn.yl.vo"/>
    </typeAliases>
</configuration>

第八步EmpMapper.xml文件

EmpMapper.xml
<?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.yl.dao.IEmpDao">
    <cache eviction="LRU" flushInterval="30000" size="500" readOnly="true"></cache>
    <!-- 编写查询的sql语句 -->
    <select id="selectById" resultType="Emp">
        SELECT *
        FROM emp
        WHERE empno = #{id}
    </select>
    <!--    删除-->
    <delete id="deleteById">
        DELETE
        FROM emp
        WHERE empno = #{0}
    </delete>
    <!--   编辑雇员信息-->
    <update id="updateById" parameterType="Emp">
        UPDATE emp SET empno=#{empno}
        <if test="ename!=null">
            ,ename=#{ename}
        </if>
        <if test="job!=null">
            ,job=#{job}
        </if>
        <if test="sal!=null">
            ,sal=#{sal}
        </if>
        WHERE empno=#{empno}
    </update>
    <!--  添加雇员信息-->
    <insert id="insertEmp" parameterType="Emp" useGeneratedKeys="true" keyProperty="empno" keyColumn="empno">
        INSERT INTO emp(empno, ename, job, sal, mgr, comm, hiredate, deptno)
        VALUES (#{empno}, #{ename}, #{job}, #{sal}, #{mgr}, #{comm}, #{hiredate}, #{deptno});
    </insert>
    <!--  模糊分页查询 -->
    <select id="selectAllSplit" resultType="Emp">
        SELECT * FROM emp WHERE 1=1
        <if test="kw!=null">
            AND ename LIKE #{kw}
        </if>
        <if test="column!=null  and sort!=null">
            ORDER BY ${column} ${sort}
        </if>
        <if test="start!=null and  ls!=null">
            LIMIT #{cp},#{ls}
        </if>
    </select>
    <!-- 批量删除数据 -->
    <delete id="deleteBatch">
        DELETE FROM emp WHERE empno IN
        <foreach collection="list" open="(" separator="," close=")" item="empno">
            #{empno}
        </foreach>
    </delete>
    <select id="selectCount" resultType="int">
        SELECT COUNT(*)
        FROM emp
        WHERE ename LIKE #{kw}
    </select>
</mapper>

配置文件类Config


@Configuration //表示该类型是作为配置类出现(定义了它的功能)
@ComponentScan(basePackages = "cn.yl")  //指定包扫描的范围
/**
 * (proxyTargetClass = true):表示不使用接口进行动态代理
 *
 */
@EnableScheduling
@EnableAspectJAutoProxy(proxyTargetClass = true) //开启动态代理
@EnableTransactionManagement //开启事务管理的支持
public class AppConfig {
    /**
     * 链接数据库信息 url username password driver
     *
     * @return 将该对象方法返回保存到ioc中
     */
    @Bean
    public DataSource dataSource() {
        //使用druid连接池链接数据库
        DruidDataSource dataSource = new DruidDataSource();
        //驱动信息
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        //连接信息
        dataSource.setUrl("jdbc:mysql://localhost:3306/demo?useSSL=true&Unicode=true&characterEncoding=UTF-8");
        //用户
        dataSource.setUsername("root");
        //密码
        dataSource.setPassword("admin");
        //创建初始连接数
        dataSource.setInitialSize(10);
        //池中最大连接数
        dataSource.setMaxActive(100);
        //池中最小连接数
        dataSource.setMinIdle(5);
        //取得最大连接的等待时间
        dataSource.setMaxWait(2000);//秒
        return dataSource;
    }

    /**
     * PlatformTransactionManager:可以为目标方法做增强,让取消事务的自动提交/事务的回滚/事务的手工提交交给代理类去完成
     * 需要使用到数据源对象  从ioc中获取
     *
     * @return transactionManager;
     */
    @Bean
    public PlatformTransactionManager transactionManager() {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource());
        return transactionManager;
    }

    /**
     * sqlsession的工厂对象 用来生产sqlsession对象的工厂
     *
     * @return
     * @throws Exception
     */
    @Bean("sqlSessionFactory")
    public SqlSessionFactoryBean sqlSessionFactoryBean() throws Exception {
        //创建sqlsession的工厂对象
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //需要取得mybatis的主配置文件(mybatic.cfg.xml) 以及映射(mapper)文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        //设置映射文件(EmpMapper.xml)
        factoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        //设置数据源对象
        factoryBean.setDataSource(dataSource());
        //设置主mybaits的配置文件
        factoryBean.setConfigLocation(resolver.getResource("classpath:mybatis.cfg.xml"));
        return factoryBean;
    }

    /**
     * 为mapper中的接口自动生成实现类
     *
     * @return
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
        scannerConfigurer.setBasePackage("cn.yl.dao");
        scannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return scannerConfigurer;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值