执行 Mapper
DalSession 方式
Mapper 文件在定义完成之后,需要加载它然后就可以通过 DalSession
接口调用它了。例如下面映射:
配置文件:/mapper/mapper_1/TestUserMapper.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>
<select id="queryListByAge">
select * from `test_user` where age = #{age}
</select>
</mapper>
加载这个映射并执行它。
DalRegistry dalRegistry = new DalRegistry();
dalRegistry.loadMapper("/mapper/mapper_1/TestUserMapper.xml");
DataSource dataSource = DsUtils.dsMySql();
DalSession dalSession = new DalSession(dataSource, dalRegistry);
Map<String, Object> ages = new HashMap<>();
ages.put("age", 26);
List<Object> result = dalSession.queryStatement("queryListByAge", ages);
对于 insert
、update
、delete
三组标签需要使用如下方式来执行,这样才能正确返回受影响行数
int result = dalSession.executeStatement("insertUser", ages);
对于 mapper
标签已经配置了 namespace
的 Mapper SQL还需要指明 namespace
。例如:
配置文件:/mapper/mapper_1/TestUserMapper.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="net.example.mapper">
<select id="queryListByAge">
select * from `test_user` where age = #{age}
</select>
</mapper>
int result = dalSession.executeStatement("net.example.mapper.queryListByAge", ages);