-
Notifications
You must be signed in to change notification settings - Fork 0
4.参数绑定
FuriousPws002 edited this page Apr 10, 2024
·
1 revision
代码分支:04-parameter-binding-with-param-annotation
本章节包含如下三种方式的参数解析
- @Param注解
- 单个参数
- 简单POJO对象
TypeHandler接口用于不同数据类型参数的处理,TypeHandlerRegistry负责注册TypeHandler,其中包含了像String,Integer等常用类型的处理器;LanguageDriver可以创建参数处理器ParameterHandler和SQL资源SqlSource,其中ParameterHandler可以设置PreparedStatement的参数,SqlSource可以获取sql语句和参数集合信息;ParamNameResolver用于参数名称解析;GenericTokenParser和TokenHandler共同实现了解析xml中sql为可执行的预处理sql,同时,提取sql参数信息为ParameterMapping。
单元测试:
public class SqlSessionTest {
/**
* Param注解绑定参数
*/
@Test
public void insertWithParam() {
Configuration configuration = new Configuration();
configuration.setDataSource(DataSourceBuilderTest.build());
configuration.addMapper(UserMapper.class);
SqlSession sqlSession = new DefaultSqlSession(configuration);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.insertWithParam("Alice", 23);
}
/**
* 支持传null
*/
@Test
public void insertWithParamNullable() {
Configuration configuration = new Configuration();
configuration.setDataSource(DataSourceBuilderTest.build());
configuration.addMapper(UserMapper.class);
SqlSession sqlSession = new DefaultSqlSession(configuration);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.insertWithParam("Jack", null);
}
/**
* 无Param注解的单个参数
* 单个参数没有设置Param注解时,无需参数名称和xml中变量名相同
*/
@Test
public void insertWithoutParam() {
Configuration configuration = new Configuration();
configuration.setDataSource(DataSourceBuilderTest.build());
configuration.addMapper(UserMapper.class);
SqlSession sqlSession = new DefaultSqlSession(configuration);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.insertWithoutParam("Tom");
}
/**
* 简单对象
*/
@Test
public void insertWithPOJO() {
Configuration configuration = new Configuration();
configuration.setDataSource(DataSourceBuilderTest.build());
configuration.addMapper(UserMapper.class);
SqlSession sqlSession = new DefaultSqlSession(configuration);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
UserDO user = new UserDO();
user.setName("Sam");
user.setAge(20);
userMapper.insertWithPOJO(user);
}
}