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 @MapperScanannotation 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 @Beanannotated 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.测试验证 三.总结 ...
随机推荐
- vc++ 最小化到托盘的详细实现
在VC++中,想实现将MFC最小化到系统托盘,需要调用NOTIFYICONDATA类,并注册相应的消息,以下详细讲解如何实现: 1.声明一个NOTIFYICONDATA类,也就是NOTIFYICOND ...
- artTemplate模板引擎的源码拜读
最初接触的模板引擎还是基于node的ejs,当时觉得很神奇原来还可以这么玩,后来随着学习的深入,使用过jade,doT等,当然还有一些比较火的诸如juicer.underscore还没有深入接触,直到 ...
- TCP/IP 协议理解
TCP/IP 协议(Transmission Control Protocol / internet Protocol),因特网互联协议,又名网络通讯协议.通俗而言:TCP负责发现传输的问题,一有问题 ...
- SqlServer 三级联动、递归表
SqlServer 省市县三级联动 三张表递归合并成一张表sql如下: insert into table2(area_name,area_parent_id) select province,'0' ...
- Entity Framework性能优化
AsNonUnicode 执行如下语句,并用SqlProfiler监控其SQL: var list = WMFactory.ReChargeMobile.Queryable().Where(w =&g ...
- jquery 关于event.target使用的几点说明介绍
event.target说明:引发事件的DOM元素. this和event.target的区别js中事件是会冒泡的,所以this是可以变化的,但event.target不会变化,它永远是直接接受事件的 ...
- Mac Zip命令
mac终端命令 zip -[parameter] [yourName].zip someFileOrDiectory -q 表示不显示压缩进度状态 -r 表示子目录子文件全部压缩为zip //这部比较 ...
- 祭奠一年前写 Direct2D demo
一年前, 用Direct2D实现了不怎么样的UI库. 用不怎么样的UI库实现了这个Demo. 当时放进某群共享, 以此装逼. 今天无意中翻出来, 解压, 什么都没变, 还是压缩前的模样. 不经意看见被 ...
- C 语言 printf格式控制详解
闲来无事,整理了一下C语言printf() 的格式控制语句. PS:详细来源于网络. printf的格式控制的完整格式: % - 0 m.n l或h 格式字符 下面对组成格式说明的各项加以说 ...
- winform下mapxtreme2008 v7.0 生成release版提示找不到dll问题
在winform下基于mapxtreme2008 v7.0 生成了一个地图软件,用debug方式运行无误,但改为release版时提示缺少一大堆dll,如: 无法从C:\Program Files ( ...