3.3.5 查询的参数传递

五、查询的参数传递

如果执行的是条件查询, 需要在调用方法时传参数进来, 此时, 可以在 select 标签中通过 parameterType 属性指定参数的类型. 而在 SQL 语句中, 可以通过#{} 的方式获取参数. 

1. 一个参数的查询

例如, 根据 id 查询用户信息. 当只有一个参数时, #{} 中可以任意填写.

<!-- parameterType, 参数类型, 用于参数的传递 -->

<select id="selById" resultType="user" parameterType="int">

<!--

#{}用于获取参数

index, 索引 , 0开始 param+数字, param1, param2

-->

select * from t_user where id=#{param1}

</select>

@Test

public void selById() {

SqlSession session = null;

try {

session = new SqlSessionFactoryBuilder()

.build(Resources. getResourceAsStream("mybatis-cfg.xml"))

.openSession();

User user =

session. selectOne("com.bjsxt.mapper.UserMapper.selById", 2);

System. out.println(user);

} catch (IOException e) {

e.printStackTrace();

} finally {

session.close();

}

}

 

2. 多个参数的查询

多个参数传递时, 由于 sqlSession 中提供的查询方法只允许传入一个参数, 因此可以对多个参数进行封装. 可以使用对象或 Map 集合.

1) 封装为对象

<select id="sel" resultType="user" parameterType="user">

<!-- 如果参数是对象, 可以通过#{属性名}来获取 -->

select * from t_user where username=#{username} and

password=#{password}

</select>

@Test

public void sel() {

SqlSession session = null;

try {

session = new SqlSessionFactoryBuilder()

.build(Resources. getResourceAsStream("mybatis-cfg.xml"))

.openSession();

User u = new User();

u.setUsername("zhangsan");

u.setPassword("123");

User user =

session.selectOne("com.bjsxt.mapper.UserMapper.sel", u);

System. out.println(user);

} catch (IOException e) {

e.printStackTrace();

} finally {

session.close();

}

}

2) 封装为 Map

<select id="sel" resultType="user" parameterType="map">

<!-- 如果参数是map, 可以通过#{key}来获取 -->

select * from t_user where username=#{uname} and password=#{upwd}

</select>

@Test

public void sel() {

SqlSession session = null;

try {

session = new SqlSessionFactoryBuilder()

.build(Resources. getResourceAsStream("mybatis-cfg.xml"))

.openSession();

Map<String, String> map = new HashMap<>();

map.put("uname", "lisi");

map.put("upwd", "123");

User user =

session.selectOne("com.bjsxt.mapper.UserMapper.sel", map);

System. out.println(user);

} 

catch (IOException e) {

e.printStackTrace();

} finally {

session.close();

}

}

猜你喜欢

转载自www.cnblogs.com/kendyho/p/10812718.html
今日推荐