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.测试验证 三.总结 ...
随机推荐
- 在命令行中如何访问Program Files文件夹(转)
通常来说Program Files文件夹位于C盘,也就是C:\Program File.为了保证兼容性,在命令行中通常使用环境变量%ProgramFiles%来表示Program Files的具体路径 ...
- php递归创建目录
/** * 递归创建目录 * @param [string] $path [创建的目录] * @return [type] [description] */ function mk_Dir($path ...
- A题笔记(5)
No. 1385 挤牛奶问题 Tips: 查找之前对数据进行一下排列会比较好; 两个“最长”放在一趟遍历里查找. class LT { public: int bt; int ct; int dura ...
- iOS与Android通用AES加密
找了很久才成功的aes 加密 服务器java写的 下载地址 https://pan.baidu.com/s/1nvi1zjr
- SQLITE和QT
sqlite3数据库支持事务 例如: BEGIN DEFERRED TRANSACTION; INSERT INTO main.test_transaction (test_unique) VALUE ...
- Bootstrap 3 支持 IE8
Bootstrap 3 支持 IE8 <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries ...
- poj 1170 Shopping Offers
Shopping Offers Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 4696 Accepted: 1967 D ...
- javascript 一串DIV跟随鼠标移动
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...
- Gvim7.4简单配置
今天下午小折腾了一会Gvim编辑器(7.4版,目前最新).看起来高端又没有代码提示,还能锻炼锻炼记忆. 修改了下默认启动配置<修改后如下图>: 打开编辑器: 编辑->启动设定-> ...
- 使用PHP对文件进行压缩解压(zip)
使用虚拟主机进行文件上传时最常用的工具莫过于FTP了,但是使用FTP有一个弊端就是文件太多时上传或下载速度比较慢,如果上传时将文件打包,上传后在 空间解压缩,同样下载前将文件打包压缩以压缩包的形式下载 ...