Mapper Interfaces and XML Mappings
Harry
· 11 Sep 2026
· 9 views
The Mapper Interface
A mapper is a simple Java interface. Each method corresponds to one SQL statement declared in XML (or via annotations).
public interface CustomerMapper {
Customer findById(Long id);
List<Customer> findByCity(String city);
void insert(Customer c);
int update(Customer c);
int delete(Long id);
}The XML Mapping File
<?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">
<mapper namespace="com.example.app.mapper.CustomerMapper">
<select id="findById" resultType="com.example.app.domain.Customer">
SELECT id, name, email, city FROM customers WHERE id = #{id}
</select>
<select id="findByCity" resultType="com.example.app.domain.Customer">
SELECT id, name, email, city FROM customers WHERE city = #{city}
</select>
</mapper>The namespace must equal the fully-qualified interface name; the statement id must equal the method name.
Parameter Name Matching
By default, MyBatis binds by name. If the XML does not see method parameter names (because they were compiled away), use @Param on the interface:
List<Customer> findByName(@Param("city") String city);Key Points
- Interface + XML of the same name form a mapper pair.
- namespace matches the interface; id matches the method.
- #{param} binds parameter values safely (PreparedStatement).
- Use @Param when parameter names might not survive compilation.