5.4 Mapper File
Use the @RefMapper annotation to associate a Mapper interface with an XML file, moving all or part of the method SQL definitions into the file. Methods not linked to the file can still use Method Annotations.
Choose a Style First
| Goal | Recommended style |
|---|---|
| Common dynamic conditions, IN queries, SET fragments | Prefer rules, which stay closer to native SQL. |
| Migrate existing MyBatis-style SQL | Use Dynamic SQL tags. |
| Map query results to DTOs | Use resultMap. |
| Map a table to an entity class | Use entity or object mapping annotations. |
Mapper interface
@RefMapper("/mapper/userMapper.xml")
public interface UserMapper {
// SQL defined via annotation
@Insert("insert into users (id, name) values (#{id}, #{name})")
int saveUser(User user);
// SQL mapped to the XML file
List<User> listUsers(@Param("searchId") long searchId);
}
userMapper.xml
<mapper namespace="net.example.mapper.UserMapper">
<select id="listUsers">
select * from users where id > #{searchId}
</select>
</mapper>
Use the Mapper
Session session = config.newSession(dataSource);
UserMapper mapper = session.createMapper(UserMapper.class);
List<User> result = mapper.listUsers(2);
Tip
How you obtain a Session depends on your project architecture. See Framework Integration for details.
User Guide
- Document Structure, the basic structure and validation of Mapper files.
- Document Tags,
<select>,<insert>,<update>,<delete>and other SQL tags (see Type Aliases). - Dynamic SQL,
<if>,<choose>,<foreach>and other tags for dynamic concatenation. - Rules, empower SQL with more dynamic capabilities via rules.
- Mapping Tables, configure Java object to database table mappings in XML.
- Mapping Result Sets, configure query result set to Java object mappings.
- Auto-Mapping, simplify
<resultMap>or<entity>configuration. - Pagination, perform pagination queries via pagination objects.