Skip to main content
Advertisement

10.1 MyBatis Overview & XML Techniques

If JPA is overwhelmingly potent for executing foundational CRUD duties alongside an object-centered architecture, MyBatis is a phenomenally advantageous SQL mapper framework utilized for outlining highly intricate statistical queries, dynamic queries (situations intertwining WHERE declarations or ORDER BY directions conditioned to specific variables), or specifically vendor-dependent (like PostgreSQL, Oracle, etc.) native SQL queries.

In legitimate business conditions, the prevalent methodology incorporates performing main data manipulatives across JPA whilst selectively implementing (substituting) MyBatis for comprehensive dashboard statistics or complicated analytical queries on admin pages.

Adding Dependencies & Configuration

Incorporate the MyBatis connection dependency inside build.gradle:

implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.3'

Secure MyBatis directives and XML file pathways within your application.yml:

mybatis:
mapper-locations: classpath:mapper/**/*.xml
configuration:
map-underscore-to-camel-case: true # This accurately cross-maps snake_case DB columns natively onto Java's camelCase variables.

Designing the Mapper Interface

Resembling JPA, MyBatis comparably institutes interfaces. However, applying a @Mapper tag broadcasts this interface implementation uniformly aligns with the targeted SQL illustrated within the XML map for the Spring compilation.

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;

@Mapper
public interface UserMapper {
// Deliver convoluted parameters (ranging from name similarity validations, restricted age filters, etc.)
List<UserStatDto> searchUserStats(@Param("keyword") String keyword, @Param("minAge") Integer minAge);
}

Designing the MyBatis XML Mapper

Advance onwards to physically compiling specific, explicit native SQL directions meticulously nestled amongst XML files analogous to src/main/resources/mapper/UserMapper.xml. MyBatis holds the massive perk of engaging dynamic tags (akin to <if>).

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- Designate formatting exactly corresponding to the namespace mimicking the underlying mapped Java folder pathway. -->
<mapper namespace="com.myapp.repository.UserMapper">

<!-- The id identity must replicate the accompanying interface method accurately; the resultType requires the fully specified route for the DTO output. -->
<select id="searchUserStats" resultType="com.myapp.dto.UserStatDto">
SELECT user_id, user_email, calculated_score AS score
FROM users
WHERE 1=1

<!-- MyBatis' primary dynamic search application: Whenever the associated parameter isn't absent (null), this constraint joins smoothly. -->
<if test="keyword != null and keyword != ''">
AND nickname LIKE CONCAT('%', #{keyword}, '%')
</if>

<if test="minAge != null">
AND age >= #{minAge}
</if>

ORDER BY created_at DESC
</select>
</mapper>

When accomplished and subsequently executing searchUserStats following proper UserMapper inclusion throughout your respective administration suite (Service class), SQL scripts dynamically built regarding the defined parameterized qualifications are directly launched toward the operational database repository. The resulting responses simultaneously transfigure systematically into formatted DTO subsets seamlessly.

Advertisement