DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Improving Backend Performance Part 1/3: Lazy Loading in Vaadin Apps
  • SQL Phenomena for Developers
  • MySQL Instant DDL: Metadata Locks, Waiting Writers, and Query Pileups

Trending

  • MQTT, Kafka, NATS, or Zenoh? Choosing Edge-to-Cloud Messaging by Traffic Pattern
  • The "Just Read the Code" Myth Is Killing Your AI Workflow
  • Introduction to Error Prone: How to Catch Bugs at Compile Time
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Databases
  4. Spring Boot: Working With MyBatis

Spring Boot: Working With MyBatis

MyBatis is a SQL framework for advanced mapping and stored procedures.

By 
Siva Prasad Reddy Katamreddy
·
Mar. 24, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
111.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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. 

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</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:

package com.sivalabs.demo.domain;
public interface UserMapper
{
    void insertUser(User user);
    User findUserById(Integer id);
    List<User> findAllUsers();
}

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:

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.sivalabs.demo.mappers.UserMapper">

    <resultMap id="UserResultMap" type="User">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="email" property="email" />
    </resultMap>

    <select id="findAllUsers" resultMap="UserResultMap">
        select id, name, email from users
    </select>

    <select id="findUserById" resultMap="UserResultMap">
        select id, name, email from users WHERE id=#{id}
    </select>

    <insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into users(name,email) values(#{name},#{email})
    </insert>
</mapper>

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: 

public interface UserMapper
{
    @Insert("insert into users(name,email) values(#{name},#{email})")
    @SelectKey(statement="call identity()", keyProperty="id",
    before=false, resultType=Integer.class)
    void insertUser(User user);

    @Select("select id, name, email from users WHERE id=#{id}")
    User findUserById(Integer id);

    @Select("select id, name, email from users")
    List<User> findAllUsers();

}

SpringBoot MyBatis starter provides the following MyBatis configuration parameters which we can use to customize MyBatis settings.

mybatis.config = mybatis config file name
mybatis.mapperLocations = mappers file locations
mybatis.typeAliasesPackage = domain object's package
mybatis.typeHandlersPackage = handler's package
mybatis.check-config-location = check the mybatis configuration exists
mybatis.executorType = mode of execution. Default is SIMPLE

Configure the typeAliasesPackage and mapperLocations in application.properties. 

mybatis.typeAliasesPackage=com.sivalabs.demo.domain
mybatis.mapperLocations=classpath*:**/mappers/*.xml

Create the entry point class SpringbootMyBatisDemoApplication.java.

@SpringBootApplication
@MapperScan("com.sivalabs.demo.mappers")
public class SpringbootMyBatisDemoApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(SpringbootMyBatisDemoApplication.class, args);
    }
}

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. 

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(SpringbootMyBatisDemoApplication.class)
public class SpringbootMyBatisDemoApplicationTests
{
    @Autowired
    private UserMapper userMapper;

    @Test
    public void findAllUsers() {
        List<User> users = userMapper.findAllUsers();
        assertNotNull(users);
        assertTrue(!users.isEmpty());
    }

    @Test
    public void findUserById() {
        User user = userMapper.findUserById(1);
        assertNotNull(user);
    }

    @Test
    public void createUser() {
        User user = new User(0, "Siva", "[email protected]");
        userMapper.insertUser(user);
        User newUser = userMapper.findUserById(user.getId());
        assertEquals("Siva", newUser.getName());
        assertEquals("[email protected]", newUser.getEmail());
    }
}

You can read more about MyBatis and Spring integration at http://blog.mybatis.org/p/products.html and http://www.mybatis.org/spring/

MyBatis Spring Framework Database sql

Published at DZone with permission of Siva Prasad Reddy Katamreddy. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Improving Backend Performance Part 1/3: Lazy Loading in Vaadin Apps
  • SQL Phenomena for Developers
  • MySQL Instant DDL: Metadata Locks, Waiting Writers, and Query Pileups

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook