Spring 4 and MyBatis Java Config
TL;DR
With the Java Config enhancements in Spring 4, you no longer need xml to configure MyBatis for your Spring application. Using the @MapperScan
annotation provided by the mybatis-spring library, you can perform a package-level scan for MyBatis domain mappers. When combined with Servlet 3+, you can configure and run your application without any XML (aside from the MyBatis query definitions). This post is a long overdue follow up to a previous post about my contribution to this code.
Class Overview
Use this annotation to register MyBatis mapper interfaces when using Java Config. It performs when same work as MapperScannerConfigurer
via MapperScannerRegistrar
.
Configuration example:
@Configuration
@MapperScan("org.mybatis.spring.sample.mapper")
public class AppConfig { @Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.addScript("schema.sql")
.build();
} @Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
} @Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
return sessionFactory.getObject();
}
}
See Also


Please note: The examples shown here work with Spring 4.0.6 and 4.2.4. Check the master branch on GitHub for updates to the version of Spring compatible with these examples.
A Java Config Appetizer
There is a lot of conflicting information out there for those searching for how to implement Spring’s Java Config. Be sure to check the version of Spring used in the example because it may not match your target version. This example uses Spring Framework 4.0.6 and MyBatis 3.2.7. As not to get into the weeds of Java Config for a Spring MCV application, we’ll cover just the pertinent parts to integrating MyBatis with Java Config.
Have a look at the file structure below. The AppInitializer
with itsAbstractAnnotationConfigDispatcherServletInitializer
super class is where life begins for the application. The getRootConfigClasses()
method returns theDataConfg
class amongst others not pictured below.
File structure:
- src/main
- java/org/lanyonm/playground
- config
* AppInitializer.java
* DataConfig.java
- domain
* User.java
- persistence
* UserMapper.java
- resources/org/lanyonm/playground
- persistence
* UserMapper.xml
* pom.xml
It’s my preference to put all the @Component
or @Configuration
classes into the config package so it’s easy to locate where the application components are configured.
The Key Files
There are four main files in this example. The first and most important isDataConfig.java
because it’s where the @MapperScan
annotation is used. On line 2, you see the package where the MyBatis mappers reside. The three @Bean
annotated methods provide the Java Config equivalent to what you would typically see in xml configuration for MyBatis. In this case aSimpleDriverDataSource
is used in place of a full-blown DataSource and specifies an in-memory H2 database. In future iterations of this application I will show how to use Spring’s Profiles to specify different DataSource implementations depending on the environment.
org.lanyonm.playground.config.DataConfig.java
:
1 |
@Configuration |
The second important piece of DataConfig
is on line 32 where we set the package containing the domain objects that will be available as types in the MyBatis xml files. Returning Java objects from SQL queries is why we go to all this ORM trouble after all.
The User domain object is really just a simple POJO. I’ve omitted the getters and setters for brevity.
org.lanyonm.playground.domain.User.java
:
1 |
public class User implements Serializable { private static final long serialVersionUID = 1L; |
MyBatis Mapper classes are simple interfaces with method definitions that match with a sql statement defined in the corresponding mapper xml. It is possible to write simple sql statements in annotations instead of defining the sql in xml, but the syntax becomes cumbersome quickly and doesn’t allow for complex queries.
org.lanyonm.playground.persistence.UserMapper.java
:
1 |
public interface UserMapper { |
I haven’t done anything special with the MyBatis xml, just a few simple statements.
org.lanyonm.playground.persistence.UserMapper.xml
:
1 |
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> |
That’s pretty much all there is to it. If you find something I left out, please let me know. The full source code for this example resides in the playground repo on GitHub.
http://blog.lanyonm.org/articles/2014/04/21/spring-4-mybatis-java-config.html
Spring 4 and MyBatis Java Config的更多相关文章
- Spring Security4实例(Java config版)——ajax登录,自定义验证
本文源码请看这里 相关文章: Spring Security4实例(Java config 版) -- Remember-Me 首先添加起步依赖(如果不是springboot项目,自行切换为Sprin ...
- Spring Security4实例(Java config 版) —— Remember-Me
本文源码请看这里 相关文章: Spring Security4实例(Java config版)--ajax登录,自定义验证 Spring Security提供了两种remember-me的实现,一种是 ...
- Spring注解@Configuration和Java Config
1.从Spring 3起,JavaConfig功能已经包含在Spring核心模块,它允许开发者将bean定义和在Spring配置XML文件到Java类中.但是,仍然允许使用经典的XML方式来定义bea ...
- Spring Web工程web.xml零配置即使用Java Config + Annotation
摘要: 在Spring 3.0之前,我们工程中常用Bean都是通过XML形式的文件注解的,少了还可以,但是数量多,关系复杂到后期就很难维护了,所以在3.x之后Spring官方推荐使用Java Conf ...
- spring、springmvc和mybatis整合(java config方式)
之前项目中使用ssm框架大多是基于xml的方式,spring3.0以后就提供java config的模式来构建项目,并且也推荐使用这种方式,自从接触过springboot后,深深感受到这种纯java配 ...
- Java DB 访问之(四) spring mvc 组合mybatis
说明 本项目采用 maven 结构,主要演示了 spring mvc + mybatis,controller 获取数据后以json 格式返回数据. 项目结构 包依赖 与说明 pom文件: <p ...
- Spring MVC 的 Java Config ( 非 XML ) 配置方式
索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: solution/pom.xml web/pom.xml web.xml WebInitializer.java ...
- spring+mybati java config配置引起的bean相互引用日志报警告问题
摘要: Error creating bean with name 'XXX': Requested bean is currently in creation: Is there an unreso ...
- Spring知识点回顾(01)Java Config
Spring知识点回顾(01) 一.Java Config 1.服务和服务注入 2.Java 注解 :功能更强一些 3.测试验证 二.注解注入 1.服务和服务注入 2.配置加载 3.测试验证 三.总结 ...
随机推荐
- Java基础知识强化之集合框架笔记62:Map集合之HashMap嵌套HashMap
1. HashMap嵌套HashMap 传智播客 jc 基础班 陈玉楼 20 高跃 ...
- Java基础知识强化之集合框架笔记61:Map集合之统计字符串中每个字符出现的次数的案例
1. 首先我们看看统计字符串中每个字符出现的次数的案例图解: 2. 代码实现: (1)需求 :"aababcabcdabcde",获取字符串中每一个字母出现的次数要求结果:a(5) ...
- 以非root权限安装nginx及运行
本章主要讲如何在无root权限(包含无sudo权限)条件下于centos命令行中安装nginx以及在大于1024的端口(这里用8080)上运行. 1. 安装 两种方式,一是下载预编译好的rpm包安装, ...
- JS获取图片上传地址
function getObjectURL(file) { var url = null ; if (window.createObjectURL!=undefined) { // basic url ...
- Object传入String类型和其他
是可以传入的. package com.sun.test; public class Test03 { /** * @param args */ public static void main(Str ...
- window.resizeTo()和window.open()
函数:window.resizeTo(width, height) 作用:改变窗口大小到设定的宽和高 参数:width - 宽度像素,必须设定的参数 height - 高度像素,可 ...
- RelativeLayout相对布局 安卓布局技巧
http://blog.csdn.net/nieweiking/article/details/38417317 RelativeLayout相对布局 相对布局 RelativeLayout 允许子元 ...
- 使用openrowset跨库查询
--insert fj_studentinfo--select *--from-- openrowset('SQLOLEDB','localhost';'sa';'password',dbname. ...
- UIKit Animation
UIKit Animation 1.属性动画 - (void)changeFrameAnimation { [UIView beginAnimations:@"frameAnimation& ...
- 查看当前linux系统位数
linux系统也有位数之分,所以在linux上安装一些软件,比如jdk之类的就需要注意下版本. 查看linux系统位数最简单的命令(这里以redhat为例,不同版本linux命令也许不同) 命令1:g ...