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
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", "[email protected]");

        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

时间: 2024-10-09 02:53:31

Spring 4 and MyBatis Java Config的相关文章

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

摘要: 在Spring 3.0之前,我们工程中常用Bean都是通过XML形式的文件注解的,少了还可以,但是数量多,关系复杂到后期就很难维护了,所以在3.x之后Spring官方推荐使用Java Config方式去替换以前冗余的XML格式文件的配置方式: 在开始之前,我们需要注意一下,要基于Java Config实现无web.xml的配置,我们的工程的Servlet必须是3.0及其以上的版本: 1.我们要实现无web.xml的配置,只需要关注实现WebApplicationInitializer这个

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

之前项目中使用ssm框架大多是基于xml的方式,spring3.0以后就提供java config的模式来构建项目,并且也推荐使用这种方式,自从接触过springboot后,深深感受到这种纯java配置的便利,但是springboot默认为我们引入好多jar和配置,使得项目变得很重,因此决定自己动手搭建一个无xml的ssm项目. 开发环境 我的开发环境如下: web服务器:tomcat8 开发工具:STS JDK版本:1.8 项目构建工具:maven 搭建过程 1.首先引入相关依赖 pom文件如

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

索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: solution/pom.xml web/pom.xml web.xml WebInitializer.java WebConfig.java RootConfig.java 一.引入必要类库 spring-context spring-context-support spring-webmvc:引入该包后,maven 会自动解析依赖,引入 spring-web 等包. 1.solution/pom.xml 1

.嵌入式jetty启动spring(java配置方式),junit测试用.标准spring 配置(java config) 嵌入式jetty9启动

package com.doctor.embeddedjetty; import java.util.concurrent.TimeUnit; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.springframework.web.con

Spring Security Java Config Preview--官方

原文地址:[1]https://spring.io/blog/2013/07/02/spring-security-java-config-preview-introduction/ [2]https://spring.io/blog/2013/07/03/spring-security-java-config-preview-web-security/ [3]https://spring.io/blog/2013/07/04/spring-security-java-config-previe

Spring Boot, Java Config - No mapping found for HTTP request with URI [/…] in DispatcherServlet with name &#39;dispatcherServlet&#39;

Spring Boot 启用应用: error: No mapping found for HTTP request with URI [/…] in DispatcherServlet with name 'dispatcherServlet' solution: @SpringBootApplication(scanBasePackages={"micro.service.basic", Spring Boot, Java Config - No mapping found for

你真的懂Spring Java Config 吗?Full @Configuration vs lite @Bean mode

Full @Configuration和lite @Bean mode 是 Spring Java Config 中两个非常有意思的概念. 先来看一下官方文档关于这两者的相关内容: The @Bean methods in a regular Spring component are processed differently than their counterparts inside a Spring @Configuration class. The difference is that

Spring、Spring MVC、MyBatis整合文件配置详解

使用SSM框架做了几个小项目了,感觉还不错是时候总结一下了.先总结一下SSM整合的文件配置.其实具体的用法最好还是看官方文档. Spring:http://spring.io/docs MyBatis:http://mybatis.github.io/mybatis-3/ 基本的组织结构和用法就不说了,前面的博客和官方文档上都非常的全面.jar包可以使用Maven来组织管理.来看配置文件. web.xml的配置                                           

Spring、Spring MVC、MyBatis

Spring.Spring MVC.MyBatis整合文件配置详解 使用SSM框架做了几个小项目了,感觉还不错是时候总结一下了.先总结一下SSM整合的文件配置.其实具体的用法最好还是看官方文档. Spring:http://spring.io/docs MyBatis:http://mybatis.github.io/mybatis-3/ 基本的组织结构和用法就不说了,前面的博客和官方文档上都非常的全面.jar包可以使用Maven来组织管理.来看配置文件. web.xml的配置