4.6 File Mapper
File Mapper is not a separate DAO form independent of Mapper API. It typically works with Mapper interfaces, moving the SQL behind interface methods from annotations into XML files.
Best For
- SQL is too long for Java annotations.
- Many dynamic SQL fragments that need centralized maintenance.
- You want SQL separated from Java code for easier review, or maintained by database-focused roles.
- You need SQL fragment reuse,
resultMapconfiguration, or XML-based object mapping.
Not Best For
- SQL is short — method annotations are more straightforward.
- Just regular single-table CRUD — prefer Mapper API (BaseMapper).
- You want SQL fully generated through chainable APIs — prefer Builder API.
Minimal Example
Mapper interface
@RefMapper("/mapper/userMapper.xml")
public interface UserMapper {
List<User> listUsers(@Param("status") String status, @Param("name") String name);
}
- Rules (recommended)
- XML tags
The Rules style keeps SQL close to native SQL, with dynamic conditions embedded directly in the statement. Prefer this for simple queries and common condition assembly.
userMapper.xml
<mapper namespace="com.example.UserMapper">
<select id="listUsers" resultType="com.example.User">
select * from users
@{and, status = :status}
@{and, name like concat(:name, '%')}
</select>
</mapper>
XML tags are useful when migrating existing MyBatis-style SQL, or when the team is already used to expressing dynamic logic through tags.
userMapper.xml
<mapper namespace="com.example.UserMapper">
<select id="listUsers" resultType="com.example.User">
select * from users
<where>
<if test="status != null">
and status = #{status}
</if>
<if test="name != null">
and name like concat(#{name}, '%')
</if>
</where>
</select>
</mapper>
With DataSource
DataSource dataSource = ...;
Configuration config = new Configuration();
Session session = config.newSession(dataSource);
UserMapper mapper = session.createMapper(UserMapper.class);
List<User> users = mapper.listUsers("ACTIVE", "A");
With Connection
Connection conn = ...;
Configuration config = new Configuration();
Session session = config.newSession(conn);
UserMapper mapper = session.createMapper(UserMapper.class);
List<User> users = mapper.listUsers("ACTIVE", "A");
Dynamic SQL Choices
Mapper files offer two kinds of dynamic SQL capabilities:
| Style | Notes | Entry |
|---|---|---|
| Rule system | @{and}, @{in}, @{set} and more — lighter-weight syntax. | SQL Rules |
| XML tags | <if>, <choose>, <foreach> and more — MyBatis-compatible style. | Dynamic SQL Tags |
Learn More
- Mapper File: XML file structure, tags, and mapping capabilities.
- SQL Statements:
select,insert,update,executeand other statement tags. - Invoking File Mapper: calling XML statements through Mapper/BaseMapper.