Hint
This article is generated by AI translation.
Mapper files
Use @RefMapper instead of @SimpleMapper to link a mapper interface to an XML file and map some or all methods to that file.
1. Link mapper interface to XML via @RefMapper
@RefMapper("/mapper/userMapper.xml")
public interface UserMapper {
// Declarative API
@Insert({ "insert into users (",
" id, name, age, create_time",
") values (",
" #{id}, #{name}, #{age}, #{createTime})",
")" })
int saveUser(User user);
// Map query to XML for more complex logic
List<User> listUsers(@Param("searchId") long searchId, List<String> prefixList);
}
2. Define some or all mapper methods in XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//dbvisitor.net//DTD Mapper 1.0//EN"
"https://www.dbvisitor.net/schema/dbvisitor-mapper.dtd">
<!-- ➊ namespace matches the mapper interface name -->
<mapper namespace="net.example.mapper.UserMapper">
<!-- ➋ select id matches the method name; result type comes from the interface method -->
<select id="listUsers">
select <include refid="userColumns"/>
from users
where owner_uid = #{searchId} and
<if test="prefixList != null and prefixList.size() > 0">
<foreach collection="prefixList" item="item" index="index" separator="or" open="and (" close=")">
#{item} like concat(res_path,'%')
</foreach>
</if>
</select>
</mapper>
3. Create and use the mapper
// 1) Create Configuration
Configuration config = new Configuration();
// 2) Create Session
Session session = config.newSession(dataSource);
或者
Session session = config.newSession(connection);
// 3) Create mapper
UserMapper mapper = session.createMapper(UserMapper.class);
List<User> result = mapper.listUsers(2, prefixList);
Quick guide
- Document: basics of mapper XML and validation.
- Doc Elements: XML tags for SQL.
- See type aliases for
<select>resultType values.
- See type aliases for
- Dynamic Command: conditionally build SQL with if/choose/foreach.
- Rules: enhance SQL via rules.
- Object Mapping: map Java objects to tables.
- Result Mapping: map query result sets.
- Auto-mapping: reduce
<resultMap>/<entity>config. - Paging: do pagination with mapper XML plus paging objects.