Skip to main content

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, resultMap configuration, 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);
}

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>
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:

StyleNotesEntry
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​