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();
   }
 }
 
 + 

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@Configuration
@MapperScan("org.lanyonm.playground.persistence")
public class DataConfig { @Bean
public DataSource dataSource() {
SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
dataSource.setDriverClass(org.h2.Driver.class);
dataSource.setUsername("sa");
dataSource.setUrl("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
dataSource.setPassword(""); // create a table and populate some data
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
System.out.println("Creating tables");
jdbcTemplate.execute("drop table users if exists");
jdbcTemplate.execute("create table users(id serial, firstName varchar(255), lastName varchar(255), email varchar(255))");
jdbcTemplate.update("INSERT INTO users(firstName, lastName, email) values (?,?,?)", "Mike", "Lanyon", "lanyonm@gmail.com"); return dataSource;
} @Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
} @Bean
public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setTypeAliasesPackage("org.lanyonm.playground.domain");
return sessionFactory;
}
}

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
2
3
4
5
6
7
8
9
10
11
public class User implements Serializable {

    private static final long serialVersionUID = 1L;
private long id;
private String firstName;
private String lastName;
private String email; // getters and setters }

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public interface UserMapper {
/**
* @return all the users
*/
public List<User> getAllUsers();
/**
* @param user
* @return the number of rows affected
*/
public int insertUser(User user);
/**
* @param user
* @return the number of rows affected
*/
public int updateUser(User user);
}

I haven’t done anything special with the MyBatis xml, just a few simple statements.

org.lanyonm.playground.persistence.UserMapper.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.lanyonm.playground.persistence.UserMapper">
<cache /> <select id="getAllUsers" resultType="User">
SELECT id, firstName, lastName, email FROM users
</select> <insert id="insertUser" parameterType="User">
INSERT INTO users (firstName, lastName, email)
VALUES (#{firstName}, #{lastName}, #{email})
</insert> <update id="updateUser" parameterType="User">
UPDATE users SET
firstName = #{firstName},
lastName = #{lastName},
email = #{email}
WHERE ID = #{id}
</update>
</mapper>

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的更多相关文章

  1. Spring Security4实例(Java config版)——ajax登录,自定义验证

    本文源码请看这里 相关文章: Spring Security4实例(Java config 版) -- Remember-Me 首先添加起步依赖(如果不是springboot项目,自行切换为Sprin ...

  2. Spring Security4实例(Java config 版) —— Remember-Me

    本文源码请看这里 相关文章: Spring Security4实例(Java config版)--ajax登录,自定义验证 Spring Security提供了两种remember-me的实现,一种是 ...

  3. Spring注解@Configuration和Java Config

    1.从Spring 3起,JavaConfig功能已经包含在Spring核心模块,它允许开发者将bean定义和在Spring配置XML文件到Java类中.但是,仍然允许使用经典的XML方式来定义bea ...

  4. Spring Web工程web.xml零配置即使用Java Config + Annotation

    摘要: 在Spring 3.0之前,我们工程中常用Bean都是通过XML形式的文件注解的,少了还可以,但是数量多,关系复杂到后期就很难维护了,所以在3.x之后Spring官方推荐使用Java Conf ...

  5. spring、springmvc和mybatis整合(java config方式)

    之前项目中使用ssm框架大多是基于xml的方式,spring3.0以后就提供java config的模式来构建项目,并且也推荐使用这种方式,自从接触过springboot后,深深感受到这种纯java配 ...

  6. Java DB 访问之(四) spring mvc 组合mybatis

    说明 本项目采用 maven 结构,主要演示了 spring mvc + mybatis,controller 获取数据后以json 格式返回数据. 项目结构 包依赖 与说明 pom文件: <p ...

  7. Spring MVC 的 Java Config ( 非 XML ) 配置方式

    索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: solution/pom.xml web/pom.xml web.xml WebInitializer.java ...

  8. spring+mybati java config配置引起的bean相互引用日志报警告问题

    摘要: Error creating bean with name 'XXX': Requested bean is currently in creation: Is there an unreso ...

  9. Spring知识点回顾(01)Java Config

    Spring知识点回顾(01) 一.Java Config 1.服务和服务注入 2.Java 注解 :功能更强一些 3.测试验证 二.注解注入 1.服务和服务注入 2.配置加载 3.测试验证 三.总结 ...

随机推荐

  1. Android开发之屏幕方向

    一.处理屏幕方向变化的两种技术 1.锚定方法 2.调整大小和重新定位,这种方法一般是分别为横向和纵向两种模式各自定义用户界面xml界面文件,当方向变化时读取对应的界面配置文件即可. 二.检测屏幕方向改 ...

  2. JS获取图片上传地址

    function getObjectURL(file) { var url = null ; if (window.createObjectURL!=undefined) { // basic url ...

  3. CentOS7上GitHub/GitLab多帐号管理SSH Key

    由于公司团队使用 GitLab 来托管代码,同时,个人在 Github 上还有一些代码仓库,可公司邮箱与个人邮箱是不同的,由此产生的 SSH key 也是不同的,这就造成了冲突 ,文章提供此类问题的解 ...

  4. ECshop--搜索模块细究

    ecshop细究 今天看了下ecshop搜索这块,前台数据一直到后台查询再返回前台.大致是这么个过程,首先,在index.dwt文件内,body下面引入了 <!-- #BeginLibraryI ...

  5. [页面辅助] 最新的 PageValidate 类 (转载)

    代码 using System; using System.Data; using System.Configuration; using System.Web; using System.Text. ...

  6. C#当中的多线程_任务并行库(上)

    复习: 第三章内容中我们提到了三种异步编程模型,这里简单复习一下,分别如下 1.APM(异步编程模式):形如Beginxxx,Endxxx. 2.EAP(基于事件的异步编程模式):这个我们在.net中 ...

  7. HTML基础(1) 全局架构标签,特殊字符

    最基本的网页文件组成部分 其中 <head></head> 这个标签对中内容不会显示在网页中 <body></body> 中的内容可以显示在网页中. b ...

  8. while loading persisted sessions 异常解决方法

    一直用tomcat一段时间都正常无事,最近一次启动tomcat就发生以下异常: 严重: IOException while loading persisted sessions: java.io.EO ...

  9. ios专题 - CocoaPods - 初次体验

    [原创]http://www.cnblogs.com/luoguoqiang1985 这CocoaPods怎么用呢? 参考官方文章:guides.cocoapods.org/using/using-c ...

  10. 祭奠一年前写 Direct2D demo

    一年前, 用Direct2D实现了不怎么样的UI库. 用不怎么样的UI库实现了这个Demo. 当时放进某群共享, 以此装逼. 今天无意中翻出来, 解压, 什么都没变, 还是压缩前的模样. 不经意看见被 ...