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.测试验证 三.总结 ...
随机推荐
- Jquery调用从ashx文件返回的jsonp格式的数据处理实例
开发环境:vs2010+jquery-1.4.min.js 解决问题:网上代码比较少,好多调试不通,返回数据不用json而用jsonp主要考虑解决跨域问题 开发步骤:打开VS2010,新建一web站点 ...
- 【Android】数据库的简单应用——创建数据库
SQLiteOpenHelper是一个抽象类,要使用它必须写一个类继承它.SQLiteOpenHelper有两个抽象方法onCreate()和onUpgrade(),我们要在类里面重写这两个方法来实现 ...
- Python获取web页面信息
import sys, urllib2 # req = urllib2.Request(sys.argv[1]) req = urllib2.Request('http://www.sina.com. ...
- python 面向对象深入理解
面向过程 函数式编程 面向对象编程:面向对象是由类和对象组成,只要用类和对象实现的,就是面向对象编程 def Bar(): print "This is Bar " ...
- 【转】char码值对应列表大全
char("56") A char("97") a [转]char码值对应列表大全 Char("0") 为0的字符Char("1& ...
- HierarchicalDataBoundControl 错误
出现以上错误原因是控件Datasources绑定出错,可能原因是没有区分树形结构的控件如Treeview的绑定与二维数据如datagridview绑定之间的区别.
- MyXLS案例
using System; using System.Data; using org.in2bits.MyXls; namespace Maticsoft.Common { /// <summa ...
- oracle学习笔记2:创建修改表
1.创建表 CREATE TABLE ORDERINFO ( ORDERID NUMBER(*, 0) NOT NULL , ORDERCODE VARCHAR2(20 BYTE) NOT NULL ...
- asp.net服务器控件开发系列一
最近想写写博客记录下自己学习开发服务器控件. 第一步:搭建环境. 1.新建一个项目类库,用于保存控件: 2.新建一个Web工程,用于调用控件: 如图: 第二步:在控件类库下,新建一个服务器控件类Tex ...
- MySQL使用指南(上)
作者:大金刚 有很多朋友虽然安装好了mysql但却不知如何使用它.在这篇文章中我们就从连接MYSQL.修改密码.增加用户等方面来学习一些MYSQL的常用命令. 一.连接MYSQL. 格式: mys ...