zoukankan      html  css  js  c++  java
  • springmvc 配置和spring配置?

    最近在接触mybatis,之间使用springmvc时,配置文件一直是,web.xml+XX-servlet.xml 的配置(xx为web.xml中servlet name名称)。
    为了整合mybatie,各种百度,发现网上很多人说的springmvc也需要配置applicationContext.xml,据我浅薄的了解,applicationContext是spring里的配置吧。所以我想问下springmvc和spring的配置区别,还有,单就springmvc和mybatis结合使用而言,配置文件究竟怎么配置。ps:目前使用的是stringbuffer形式的拼接sql,结合org.springframework.jdbc中的nameparameterjdbctemplate来使用的,想换换新的使用,望各位不吝赐教,感谢)

    ====================================================================================

    作者:二流程序猿
    链接:https://www.zhihu.com/question/47565214/answer/136096996
    来源:知乎
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    springMVC负责spring控制层的处理,而servlet.xml配置文件,主要负责MVC这部分的配置,如视图解析、上下文处理等,这里要注意的是,此文件的名称与位置是允许在web.xml的servlet配置中定义的(init-param):

     <servlet>
            <servlet-name>graduation</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring-servlet.xml</param-value>
            </init-param>
            <load-on-startup>2</load-on-startup><!--表示启动容器时候初始化-->
        </servlet>
        <servlet-mapping>
            <servlet-name>graduation</servlet-name>
            <url-pattern>/</url-pattern><!--表示对所有后缀为do的请求做spring拦截-->
        </servlet-mapping>
    
    而application.xml用来配置spring的全局属性,例如datasource、aop等,首先要在web.xml中添加配置(classpath:applicationContext.xml的路径):
    <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring-applicationContext.xml</param-value>
    </context-param>
    

    下面就是如何将spring与mybatis相结合了
    在applicationContext.xml这个配置文件中,我们要先配置我们的数据源:
    具体配置以项目为准,这里用的是阿里的druid。
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
            <!--驱动名称-->
            <property name="driverClassName" value="${jdbc.driverClassName}"/>
            <!--JDBC连接串-->
            <property name="url" value="${jdbc.url}"/>
            <!--数据库名称-->
            <property name="username" value="${jdbc.username}"/>
            <!--数据库密码-->
            <property name="password" value="${jdbc.password}"/>
            <!--初始化大小-->
            <property name="initialSize" value="15"/>
            <!--连接池最大使用数量-->
            <property name="maxActive" value="20"/>
            <!--连接池最小空闲-->
            <property name="minIdle" value="0"/>
            <!--配置获取连接等待超时时间-->
            <property name="maxWait" value="60000"/>
            <!--配置间隔多久才进行一次检测 , 检测需要关闭的空闲连接-->
            <property name="timeBetweenEvictionRunsMillis" value="60000"/>
            <!--配置一个连接在池中最小生存时间-->
            <property name="minEvictableIdleTimeMillis" value="300000"/>
            <!--连接空闲时测试是否有效-->
            <property name="testWhileIdle" value="false"/>
            <!--获取连接时测试是否有效-->
            <property name="testOnBorrow" value="false"/>
            <!--归还连接时测试是否有效-->
            <property name="testOnReturn" value="false"/>
            <!--打开PSCache , 并指定每个连接上PSCache的大小-->
            <property name="poolPreparedStatements" value="false"/>
            <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
        </bean>
    

    下面同样在applicationContext.xml这个配置文件中,添加mybaits的配置(包括事物):
    <!--mybatis sessionFaction 实例-->
    <bean id="sqlSessionFaction" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--mapper.xml 映射-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <!--pojo映射 , 这里映射到POJO包-->
        <property name="typeAliasesPackage" value="com.graduation.pojo"/>
    </bean>
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.graduation.dao" />
    </bean>
    <!--mybatis 事物配置-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 事务注解驱动,标注@Transactional的类和方法将具有事务性 -->
    <tx:annotation-driven transaction-manager="txManager" />
    

    下面就是如何使用了
    mybaits必不可少的mapper.xml、dao、pojo类。这里如何自己去编写这些内容楼主应该可以搞定 , 要注意的是路径要与上述配置路径匹配。同样,也可以借助genertor等去自动生成这些文件。
    可参考:使用Mybatis-Generator自动生成Dao、Model、Mapping相关文件(转) - 斗爷 - 博客园
    同样我们在做交互操作时候也非常简单,没有必要对sessionFactory的生命周期负责了,spring全权负责。

    下面是我通过generator生成的测试demo:
    pojo:
    public class Test {
    private Long id;
    
        private String test;
    
    
        public Long getId() {
    return id;
        }
    
    public void setId(Long id) {
    this.id = id;
        }
    
    public String getTest() {
    return test;
        }
    
    public void setTest(String test) {
    this.test = test == null ? null : test.trim();
        }
    
    }
    

    dao:
    // 这是我们Test类的dao层
    
    //这是spring的注解,有了它我们就可以通过spring的@Autowired实例化该类
    @Repositorypublic interface TestDao {
        // 下面为CRUD操作
        int deleteByPrimaryKey(Long id);   
        int insert(Test record);    
        int insertSelective(Test record);    
        Test selectByPrimaryKey(Long id);    
        int updateByPrimaryKeySelective(Test record);   
        int updateByPrimaryKey(Test record);
    }
    

    mapper.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="com.graduation.dao.TestMapper" >
      <resultMap id="BaseResultMap" type="com.graduation.domain.Test" >
        <id column="id" property="id" jdbcType="BIGINT" />
        <result column="test" property="test" jdbcType="VARCHAR" />
      </resultMap>
      <sql id="Base_Column_List" >
        id, test
    </sql>
      <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
        select 
    <include refid="Base_Column_List" />
        from test
        where id = #{id,jdbcType=BIGINT}
    </select>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
        delete from test
        where id = #{id,jdbcType=BIGINT}
    </delete>
      <insert id="insert" parameterType="com.graduation.domain.Test" >
        insert into test (id, test
          )
        values (#{id,jdbcType=BIGINT}, #{test,jdbcType=VARCHAR}
          )
    </insert>
      <insert id="insertSelective" parameterType="com.graduation.domain.Test" >
        insert into test
    <trim prefix="(" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            id,
    </if>
          <if test="test != null" >
            test,
    </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            #{id,jdbcType=BIGINT},
    </if>
          <if test="test != null" >
            #{test,jdbcType=VARCHAR},
    </if>
        </trim>
      </insert>
      <update id="updateByPrimaryKeySelective" parameterType="com.graduation.domain.Test" >
        update test
    <set >
          <if test="test != null" >
            test = #{test,jdbcType=VARCHAR},
    </if>
        </set>
        where id = #{id,jdbcType=BIGINT}
    </update>
      <update id="updateByPrimaryKey" parameterType="com.graduation.domain.Test" >
        update test
        set test = #{test,jdbcType=VARCHAR}
        where id = #{id,jdbcType=BIGINT}
    </update>
    </mapper>
    

    然后我们通过测试类运行这个demo(这里不能通过main测试):
    // 测试时候不能在main里面执行,因为main方法不会读取spring的配置文件
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"/spring-applicationContext.xml"})
    public class tets {
        @Autowired
        private TestDao testDao; // 这是我们的dao 不要被名字迷惑...
        
        @Test
        public void testSearchallUser() {
            Test test = Test();
            test.setTest("123");
            testDao.insert(test) ;
        }
    }
    
    这样就OK了 !
  • 相关阅读:
    iOS 获取当前界面所在的视图控制器
    the executable was signed with invalid 解决方法
    iOS 中一些代码规范
    In order to validate a domain name for self signed certificates, you MUST use pinning,AFNetWorking使用自签证书时出现问题。
    IOS -- SQLite数据库判断表是否存在
    如何解决 iOS The document “(null)” requires Xcode 8.0 or later. 不能编译的问题
    iOS开发 如何适配iOS10
    更新cocoapods之后,出现Undefined symbols for architecture arm64
    新的一天
    css布局之弹性布局
  • 原文地址:https://www.cnblogs.com/soundcode/p/6472442.html
Copyright © 2011-2022 走看看