Spring Boot: Working With MyBatis
MyBatis is a SQL Mapping framework with support for custom SQL, stored procedures and advanced mappings.
SpringBoot doesn’t provide official support for MyBatis integration, but the MyBatis community built a SpringBoot starter for MyBatis.
You can read about the SpringBoot MyBatis Starter release announcement at http://blog.mybatis.org/2015/11/mybatis-spring-boot-released.html and you can explore the source code on GitHub https://github.com/mybatis/mybatis-spring-boot.
Create a SpringBoot Maven project and add the following MyBatis Starter dependency.
We will be reusing User.java, schema.sql and data.sql files created in my previous article SpringBoot : Working with JdbcTemplate
Create MyBatis SQL Mapper interface UserMapper.java with few database operations as follows:
We need to create Mapper XML files to define the queries for the mapped SQL statements for the corresponding Mapper interface methods.
Create UserMapper.xml file in src/main/resources/com/sivalabs/demo/mappers/ directory as follows:
A few things to observe here are:
- Namespace in Mapper XML should be same as Fully Qualified Name (FQN) for Mapper Interface
- Statement id values should be same as Mapper Interface method names.
- If the query result column names are different from bean property names we can use <resultMap> configuration to provide mapping between column names and their corresponding bean property names.
MyBatis also provides annotation based query configurations without requiring Mapper XMLs.
We can create UserMapper.java interface and configure the mapped SQLs using annotations as follows:
SpringBoot MyBatis starter provides the following MyBatis configuration parameters which we can use to customize MyBatis settings.
Configure the typeAliasesPackage and mapperLocations in application.properties.
Create the entry point class SpringbootMyBatisDemoApplication.java.
Observe that we have used @MapperScan("com.sivalabs.demo.mappers") annotation to specify where to look for Mapper interfaces.
Now create a JUnit test class and test our UserMapper methods.
You can read more about MyBatis and Spring integration at http://blog.mybatis.org/p/products.html and http://www.mybatis.org/spring/
No comments:
Post a Comment