MyBatis是一个优秀的轻量级持久化框架,本文主要介绍MyBatis与Spring集成的配置与用法。

1. Spring MyBatis配置

1.1 添加Maven依赖

在pom.xml文件里添加mybatis-spring和mybatis的依赖:

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>

mybatis-spring当前最新版本为1.2.2,mybatis当前版本是3.2.5.

1.2 添加dao接口

这里的dao必须是接口,而不是具体的实现,如MyBatisDao.java内容为:

public interface MyBatisTest {
public String getUserNameById(int id);
public List<Students> getStudentByNumAndCity(Map<String, Object> queryMap);
}

接口中定义的每一个方法对应于mapper映射文件中定义的jdbc执行模块,如<select/><update/><insert/>等。

1.3 添加mybatis配置文件

该配置文件里主要配置类型别名<typeAliases/>、设置<settings/>,mapper映射文件路径<mappers/>也可以放在这里,但更建议将所有的mapper文件都放在一个目录下,在定义sqlSessionFactory时通过属性mapperLocations指定。如mybatis.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>
<typeAliases>
<typeAlias type="com.sohu.tv.bean.Students" alias="Students"/>
</typeAliases>
<!--<mappers>-->
<!--<mapper resource="com/sohu/tv/mapper/MybatisTest.xml"/>-->
<!--</mappers>-->
</configuration>

类型别名是用别名来代表全限定类名,如在需要用到com.sohu.tv.bean.Students的地方,都可以使用Students来代替。

1.4 添加mapper映射文件:

mapper映射文件可以定义数据库列与POJO类属性的映射,以及与dao接口类中的方法对应的JDBC执行模块,如MyBatisMapper.xml的内容为:

<mapper namespace="com.sohu.tv.dao.MyBatisTest">
<resultMap id="studentMap" type="Students">
<result column="name" property="name"/>
<result column="sex" property="sex"/>
<result column="number" property="number"/>
<result column="enable" property="enable"/>
<result column="city" property="city"/>
</resultMap>
<select id="getUserNameById" parameterType="int" resultType="String">
select name from students where id = #{id}
</select>
<select id="getStudentByNumAndCity" parameterType="map" resultMap="studentMap">
select * from students where number = #{num} and city = #{city}
</select>
</mapper>

<resultMap/>即定义列与属性的字段映射;<select/>中的参数和返回值的类型,既可以为基本类型,如string,int,long,也可以是map,返回类型还可以是<resultMap/>定义的映射map;如果参数类型是map,则sql中的参数名(如#{num})必须是map的key;如果返回类型为map,则sql语句中返回的列名为key;如果是基本类型,使用type,如parameterType,resultType,如果是自定义map,使用parameterMap,resultMap.

1.5 Spring配置文件的配置

首先需要配置sqlSessionFactory:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="feedbackDataSource"/>
<property name="configLocation" value="classpath:mybatis.xml"/>
<property name="mapperLocations" value="classpath:com/sohu/tv/mapper/*.xml"/>
</bean>

属性dataSource引用JDBC数据源;属性configLocation指定mybatis配置文件的位置,配置文件中定义别名<typeAliases/>,设置<settings/>等。mapperLocations指定mapper映射文件的路径。有一点需要注意的是,要确保mapper映射文件被打包进classpath中,默认情况下,maven会忽略源文件中的资源文件,可以通过在pom文件中配置,使得资源文件被一起打包进classpath中;如在pom配置文件中添加:

<build>
<resources>
<resource>
<directory>src/main/java</directory>
<excludes><exclude>**/*.java</exclude></excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>

其次,需要定义与dao接口相关联的mapperFactoryBean:

<bean id="mybatisDaoImpl" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.sohu.tv.dao.MyBatisTest"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

mapperInterface属性的值为相关的dao接口,sqlSessionFactory属性引用了上述定义的sqlSessionFacotry;

1.6 service类中调用dao类实现业务逻辑

在MyBatisServiceImpl.java中使用dao接口中提供的方法:

@Resource(name = "mybatisDaoImpl")
MyBatisDao myBatisDaoImpl;
String userName = mybatisDaoImpl.getUserNameById(2);
System.out.println(userName);
Map<String, Object> queryMap = new HashMap<String, Object>();
queryMap.put("num", 333);
queryMap.put("city", "beijing");
List<Students> studentsList = mybatisDaoImpl.getStudentByNumAndCity(queryMap);
for (Students students: studentsList) {
System.out.println(students.getName());
}

2. 启动自动扫描注解

我们可以在applicationContext.xml配置文件里为每个dao接口定义bean,但mybatis还提供了一种更简便的自动扫描注解的机制,即<mybatis:scan/><MapperScannerConfigurer/>。 配置<mybatis:scan/>,需要在applicationContext.xml配置文件里添加:

<mybatis:scan base-package="com.sohu.tv.dao"/>

<mybatis:scan/>与Spring的<context:component-scan/>非常相似,base-package指定要扫描的包,并将包下的所有接口注册为对应的bean。命名规则:和Spring一样,如果该接口没有被注解,则bean的名称为首字母小写的非限定类名,如接口为com.sohu.tv.dao.MyBatisDao,则bean的名字为myBatisDao;如果dao接口使用了Spring的注解,如@Component或@Named等注解,并提供了bean的名称,则mybatis使用该注解的名称作为bean的名称。如将MyBatisDao接口重定义如下:

@Repository(value = "mybatisDao")
public interface MyBatisDao {
public String getUserNameById(int id);
public List<Students> getStudentByNumAndCity(Map<String, Object> queryMap);
}

测试MyBatisDao被自动注解后的bean的名称为mybatisDao。建议通过注解指定bean的名称,防止类类名的变化导致了bean名称的变化;

配置<MapperScannerConfigurer/>,需要在applicationContext.xml中添加:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.sohu.tv.dao"/>
<property name="sqlSessionFactoryBeanName" value = "sqlSessionFactory"/>
</bean>

这里的basePackage<mybatis:scan/>base-package的含义一致,bean的命名规则也是一样的,所以这两种方式等价。

如果启动了自动扫描注解,则在spring配置文件中不再需要dao接口的bean定义了。

3. 总结-最佳实践

  • mapper映射文件放在单独的目录中,统一管理,在配置sqlSessionFactory时,通过属性mapperLocations指定;
  • mybatis配置文件中只定义typeAliasessettings等配置信息;
  • Spring配置文件中,通过<mybatis:scan/>或者<MapperScannerConfigurer/>启动自动注解,并通过Spring的注解对bean命名。

Spring持久化之MyBatis的更多相关文章

  1. ssm(spring,spring mvc,mybatis)框架

    ssm框架各个技术的职责 spring :spring是一个IOC DI AOP的 容器类框架 spring mvc:spring mvc 是一个mvc框架 mybatis:是一个orm的持久层框架 ...

  2. spring MVC、mybatis配置读写分离

    spring MVC.mybatis配置读写分离 1.环境: 3台数据库机器,一个master,二台slave,分别为slave1,slave2 2.要实现的目标: ①使数据写入到master ②读数 ...

  3. Spring、Spring MVC、MyBatis整合文件配置详解

    原文  http://www.cnblogs.com/wxisme/p/4924561.html 主题 MVC模式MyBatisSpring MVC 使用SSM框架做了几个小项目了,感觉还不错是时候总 ...

  4. spring mvc与mybatis收集到博客

    mybaits-spring 官方教程 http://mybatis.github.io/spring/zh/ SpringMVC 基础教程 框架分析 http://blog.csdn.net/swi ...

  5. spring.net 和 mybatis.net

    demo是整合现有的spring.net 和 mybatis.net 完成的控制台程序,需要注意的地方:关于Config文件夹中的config文件的属性设定:同时保证Providers.config默 ...

  6. 搭建Spring、Spring MVC、Mybatis和Freemarker

    搭建Spring.Spring MVC.Mybatis和Freemarker 1.pom文件 <project xmlns="http://maven.apache.org/POM/4 ...

  7. Spring Mvc和Mybatis的多数据库访问配置过程

    Spring Mvc 加Mybatis的多数据库访问源配置访问过程如下: 在applicationContext.xml进行配置 <?xml version="1.0" en ...

  8. Spring、Spring MVC、MyBatis

    Spring.Spring MVC.MyBatis整合文件配置详解 使用SSM框架做了几个小项目了,感觉还不错是时候总结一下了.先总结一下SSM整合的文件配置.其实具体的用法最好还是看官方文档. Sp ...

  9. IDEA下创建Maven项目,并整合使用Spring、Spring MVC、Mybatis框架

    项目创建 本项目使用的是IDEA 2016创建. 首先电脑安装Maven,接着打开IDEA新建一个project,选择Maven,选择图中所选项,下一步. 填写好GroupId和ArtifactId, ...

随机推荐

  1. CodeForces 644B【模拟】

    题意: 查询数 和 最大的队列容量+1: 按时间顺序 ti代表,第i个出线的时间: di代表,第i个需要处理的时间: 对于第i个输出他所需要的时间完成,或者拒绝进入输出-1: 思路: 真是MDZZ了, ...

  2. 卡马克揭开VR延迟背后的真相

    原文:http://oculusrift-blog.com/john-carmacks-message-of-latency/682/ 延迟是OculusVR所面对的最大挑战之一,  它不仅会分散玩家 ...

  3. Unity3D研究院之手游开发中所有特殊的文件夹

    这里列举出手游开发中用到了所有特殊文件夹. 1.Editor Editor文件夹可以在根目录下,也可以在子目录里,只要名子叫Editor就可以.比如目录:/xxx/xxx/Editor  和 /Edi ...

  4. Pycharm 配置autopep8到菜单

    Pycharm 可以自动检测PEP8规范. 我们可以安装autopep8来自动修改文件实现PEP8规范. 1.通过Pycharm安装autopep8 2.File->Setting->Ex ...

  5. Xmind8 Pro 思维导图制作软件,傻瓜式安装激活教程

    xmind 是做思维导图的软件?今天有一个以前的同事还在和我要这个软件,当然我支持正版啊 !因为正版好用! 我是一个不爱说废话的人,就顺便分享一下 给大家用! 软件下载地址: 链接:https://p ...

  6. react-native-wechat微信组件的使用

    对我来说link没有成功过,所以参考了其他人的文章,原文:https://www.jianshu.com/p/6a792118fae4 第一步:要去:https://open.weixin.qq.co ...

  7. [題解](最短路)luogu_P2384最短路

    hack: 4 4 1 2 10000 2 3 10000 3 4 10000 1 4 10000 答案:13 不能邊最短路邊取模,因為取模后最大值不一定為原來最大值,所以利用log(m*n)=log ...

  8. LSP5513

    LSP5513:宽范围高效的DC-DC(输入:4.5~27V;输出0.925~24V,3A),输出电流达3A

  9. Bridges Gym - 100712H  无向图的边双连通分量,Tarjan缩点

    http://codeforces.com/gym/100712/attachments 题意是给定一个无向图,要求添加一条边,使得最后剩下的桥的数量最小. 注意到在环中加边是无意义的. 那么先把环都 ...

  10. laravel 5.5 oauth2.0 跨域问题解决方案

    一.laravel-Cors 安装 在终端执行安装命令如下: composer require barryvdh/laravel-cors 添加服务提供商 在Laravel配置文件app.php的pr ...