Spring 4 and MyBatis Java Config

Source: Internet
Author: User

Tl;dr

With the Java Config enhancements in spring 4, you are no longer need XML to configure MyBatis for your Spring application. Using the @MapperScan annotation provided by the Mybatis-spring library, you can perform a package-level scan for Mybati s domain mappers. When combined with Servlets, you can configure and run your application without any XML (aside from the MyBatis query de finitions). This post was a long overdue follow up to a previous post about my contribution to this code.

Class Overview

Use the 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 DataSourceDataSource() {
Return New Embeddeddatabasebuilder()
.Addscript("Schema.sql")
.Build();
}

@Bean
Public DatasourcetransactionmanagerTransactionManager() {
Return New Datasourcetransactionmanager(DataSource());
}

@Bean
Public SqlsessionfactorySqlsessionfactory() Throws exception {
     sqlsessionfactorybean sessionfactory = new sqlsessionfactorybean ();      sessionfactory. Setdatasource (datasource ());      return Sessionfactory.    }
 }
 

See Also
    • MapperScannerRegistrar
    • MapperFactoryBean

+

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 Integrat ing MyBatis with Java Config.

There is a look at the file structure below. The WITH it AppInitializer AbstractAnnotationConfigDispatcherServletInitializer Super class is where life begins for the application. The getRootConfigClasses() method returns the DataConfg 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 or classes into the Config package so it's easy to @Component @Configuration locate where the Applicat Ion components is configured.

The Key Files

There is four main files on this example. The first and most important are DataConfig.java because it's where the @MapperScan annotation is used. On line 2, you see the package where the MyBatis mappers reside. The three @Bean annotated methods provide the Java Config equivalent to what are would typically see in XML configuration F or MyBatis. In this case a was used in place of SimpleDriverDataSource a full-blown DataSource and specifies an in-memory H2 database. In the future iterations of this application I'll show how to use Spring's Profiles to specify different DataSource implemen Tations depending on the environment.

Org.lanyonm.playground.config. DataConfig.java :

1234567891011121314151617181920212223242526272829303132333435
@Configuration@MapperScan("Org.lanyonm.playground.persistence")PublicClassDataconfig{@BeanPublicDataSourceDataSource(){SimpledriverdatasourceDataSource=NewSimpledriverdatasource();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 dataJdbcTemplateJdbcTemplate=NewJdbcTemplate(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]");ReturnDataSource;}@BeanPublicDatasourcetransactionmanagerTransactionManager(){ReturnNewDatasourcetransactionmanager(DataSource());} @Bean public sqlsessionfactorybean  Sqlsessionfactory () throws exception { sqlsessionfactorybean sessionfactory = new sqlsessionfactorybean (); sessionfactory. (datasource ()); sessionfactory. ( "Org.lanyonm.playground.domain" return sessionfactory}             /span>                 

The second important piece of is on line + DataConfig where we set the package containing the domain objects that'll be Avai Lable as types in the MyBatis XML files. Returning Java objects from SQL queries are why do we go to all this ORM trouble through 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 :

1234567891011
 public class user  Implements serializable {private static final long serialversionuid = 1Lprivate long idprivate string firstnameprivate string lastnameprivate string email//getters and Setters           

MyBatis Mapper classes is simple interfaces with method definitions this match with a SQL statement defined in the Corres Ponding Mapper XML. It is possible-write simple SQL statements in annotations instead of defining the SQL in XML, but the syntax becomes CU Mbersome quickly and doesn ' t allow for complex queries.

Org.lanyonm.playground.persistence. UserMapper.java :

12345678910111213141516
 public interface usermapper {/** * @return all the users */public list<user> getallusers (); /** * @param user * @return The number of rows affected */public int span class= "n" >insertuser (user user/** * @param user * @return The number of rows affected */public int span class= "n" >updateuser (user user}  

I Haven ' t do anything special with the MyBatis XML, just a few simple statements.

Org.lanyonm.playground.persistence. UserMapper.xml :

123456789101112131415161718192021
<! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapperNamespace="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 are to it. If you find something I left off, please let me know. The full source code is 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.