最近在接触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了 !

springmvc 配置和spring配置?的更多相关文章

  1. SpringMVC之二:配置 Spring MVC

    Servlet 3.0规范在2009年12月份就发布了,因此很有可能你会将应用部署到支持Servlet 3.0的Servlet容器之中,如tomcat7.0及以上.在Servlet 3 规范中,可以使 ...

  2. Spring 和 SpringMVC 常用注解和配置(@Autowired、@Resource、@Component、@Repository、@Service、@Controller的区别)

    Spring 常用注解 总结内容 一.Spring部分 1.声明bean的注解 2.注入bean的注解 3.java配置类相关注解 4.切面(AOP)相关注解 5.事务注解 6.@Bean的属性支持 ...

  3. SSM三大框架整合配置(Spring+SpringMVC+MyBatis)

    web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi=" ...

  4. (转)springMVC+mybatis+ehcache详细配置

    一. Mybatis+Ehcache配置 为了提高MyBatis的性能,有时候我们需要加入缓存支持,目前用的比较多的缓存莫过于ehcache缓存了,ehcache性能强大,而且位各种应用都提供了解决方 ...

  5. MyBatis学习(一)、MyBatis简介与配置MyBatis+Spring+MySql

    一.MyBatis简介与配置MyBatis+Spring+MySql 1.1MyBatis简介 MyBatis 是一个可以自定义SQL.存储过程和高级映射的持久层框架.MyBatis 摒除了大部分的J ...

  6. Spring配置汇总

    现在主流的JavaWeb应用几乎都会用到Spring,以下是Spring的配置,以及结合Web的SpringMVC配置的汇总. jar包的引入 与Web项目集成 Spring配置文件 SpringMV ...

  7. 基于XML配置的Spring MVC 简单的HelloWorld实例应用

    1.1 问题 使用Spring Web MVC构建helloworld Web应用案例. 1.2 方案 解决本案例的方案如下: 1. 创建Web工程,导入Spring Web MVC相关开发包. Sp ...

  8. spring配置详解

    1.前言 公司老项目的后台,均是基于spring框架搭建,其中还用到了log4j.jar等开源架包.在新项目中,则是spring和hibernate框架均有使用,利用了hibernate框架,来实现持 ...

  9. MyBatis学习 之 一、MyBatis简介与配置MyBatis+Spring+MySql

    目录(?)[-] 一MyBatis简介与配置MyBatisSpringMySql MyBatis简介 MyBatisSpringMySql简单配置 搭建Spring环境 建立MySql数据库 搭建My ...

随机推荐

  1. MySQL Table Information

    show tables;                    --显示该数据库里的所有表show columns from 表名;         --显示表字段use information_sc ...

  2. [转载]FFmpeg完美入门[3] - FFmpeg功能及使用说明

    1 ffplay对多媒体的支持能力验证 一.视频3gp 177X144 支持播放,在windows下播放正常,但是在linux下面偶有BUG 如果发现画面无法显示而声音可以播放的情况下可以试着切换全屏 ...

  3. 在ubuntu上安装Chrome

    1.下载谷歌浏览器源文件.链接有很多,以下是64位版本的下载地址 https://dl.google.com/linux/direct/google-chrome-stable_current_amd ...

  4. [ python ] 匿名函数和高阶函数

    匿名函数 描述:    关键字 lambda 定义的函数    语法: 函数名 = lambda 参数:返回值 返回值:    函数返回结果值 实例: 一个参数的匿名函数: func = lambda ...

  5. TreeSet基本用法

    TreeSet的基础方法: public class TreeSetTest { public static void main(String[] args) { TreeSet nums = new ...

  6. StringBuilder基本用法

    //StringBuilder用法 public class StringBuilderTest { public static void main(String[] args) { StringBu ...

  7. 关于VS2010的一些操作

    自动插入接口实现 1: class MyClass : IMyInterface 2: { 3:   4: } .csharpcode, .csharpcode pre { font-size: sm ...

  8. 查看wtmp(登陆信息的内容)

      /var/log/wtmp文件的作用     /var/log/wtmp也是一个二进制文件,记录每个用户的登录次数和持续时间等信息.   查看方法:   可以用last命令输出当中内容: debi ...

  9. js中的for循环

    预定义: var arr=[22,33,12,34];//数组(特殊的对象) var obj={ //对象 name:"Jack", age:"99", sex ...

  10. ssh客户端乱码

    export LC_ALL=zh_CN.GB2312;export LANG=zh_CN.GB2312