Annotation vs XML Mapper in MyBatis: Pros, Cons, and How to Choose
This article compares MyBatis’s fully‑annotation mode and the mixed interface‑plus‑XML mode, outlining their implementation examples, advantages, disadvantages, and providing guidance on selecting the appropriate approach based on project size, query complexity, and team collaboration needs.
Annotation Mode
Annotation mode is straightforward: add annotations like @Select and @Insert directly in the Mapper interface to control SQL.
Implementation Example
Basic user Mapper:
@Mapper
public interface UserMapper {
@Insert("INSERT INTO user (username, password, role) VALUES (#{username}, #{password}, #{role})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insertUser(User user);
@Select("SELECT * FROM user WHERE username = #{username}")
User findByUsername(String username);
@Update("UPDATE user SET password = #{password} WHERE id = #{id}")
void updatePassword(@Param("id") Integer id, @Param("password") String password);
}Advantages
Simple file composition, intuitive.
SQL statements are clear and reduce errors for simple interfaces.
Suitable for small applications or simple tables.
Disadvantages
SQL embedded in code leads to bloated files and hard maintenance for complex queries.
Poor extensibility; dynamic conditions are hard to implement.
Collaboration difficulty: developers must know both SQL and Java, increasing communication cost.
Mixed Mode
Mixed mode uses “interface declaration + XML configuration file”. The Mapper interface defines method signatures, while SQL resides in XML.
Implementation Example
Complex tour line query Mapper:
@Mapper
public interface TourLineMapper {
List<TourLine> filterTourLines(@Param("destination") String destination,
@Param("minPrice") Double minPrice,
@Param("maxPrice") Double maxPrice,
@Param("minDuration") Integer minDuration,
@Param("maxDuration") Integer maxDuration);
}Corresponding XML snippet:
<select id="filterTourLines" parameterType="map" resultType="TourLine">
SELECT * FROM tour_line
WHERE 1 = 1
<if test="destination != null">AND destination = #{destination}</if>
<if test="minPrice != null">AND price >= #{minPrice}</if>
<if test="maxPrice != null">AND price <= #{maxPrice}</if>
<if test="minDuration != null">AND duration >= #{minDuration}</if>
<if test="maxDuration != null">AND duration <= #{maxDuration}</if>
</select>Structure Explanation
filterTourLinesdefines the query method matching the Java interface. parameterType="map" indicates parameters are passed as a Map via @Param. resultType="TourLine" specifies the result object type.
Dynamic Conditions
Using <if> tags allows conditional SQL fragments based on parameter presence, preventing errors and enabling flexible query building.
Best Practices
Keep SQL in XML for readability and maintainability.
Ensure parameter names in XML match @Param annotations.
Use <choose> and <when> for more complex logic such as dynamic ordering.
Advantages
Elegant SQL implementation with flexible condition handling.
Separation of concerns reduces coupling between Java and SQL.
Well‑suited for complex queries and large projects.
Disadvantages
Higher learning curve; requires knowledge of both interface and XML syntax.
SQL scattered across files makes debugging less convenient.
Development speed may be slower compared to full‑annotation mode for small projects.
How to Choose?
If the project is small with simple tables and basic CRUD, use annotation mode for rapid development.
If the project is large with complex, dynamic queries, prefer mixed mode for flexibility and maintainability.
For team collaboration, mixed mode’s separation reduces communication overhead when SQL changes frequently.
Regardless of the choice, select the approach that best fits the project’s requirements and team workflow.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
