Hint
This article is generated by AI translation.
File Mapper
When dealing with long queries, the Programmatic API, Declarative API, or Fluent API can become less readable due to complexity. In these cases, putting complex SQL in a dedicated mapper file is the best choice.
Highlights
- Focuses on centralized SQL management via Mapper XML, while still allowing execution through mapper interfaces—great for complex SQL management.
- Mapper files extend the Declarative API, so mixing them is recommended.
1. Link mapper to the UserMapper interface; file at: classpath:/mapper/userMapper.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">
<mapper namespace="com.example.UserMapper">
<insert id="insertBean">
insert into users (id,name) values (#{id}, #{name})
</insert>
<select id="listUsers" resultType="com.example.User">
select * from users
</select>
</mapper>
2. Use @RefMapper to link mapper file
@RefMapper("/mapper/userMapper.xml")
public interface UserMapper{
// Maps to: insert into users ...
int insertBean(User user);
// Maps to: select * from users ...
List<User> listUsers();
}
3. Create the mapper
// 1. Create Configuration
Configuration config = new Configuration();
// 2. Create Session
Session session = config.newSession(dataSource);
Or
Session session = config.newSession(connection);
// 3. Create BaseMapper
UserMapper mapper = session.createMapper(UserMapper.class);
details