el-select传递多个参数_带参数的查询-MyBatis(7)

5e85d79b510a094578f6a61595958e32.png

1. 带参数的查询

如果执行的是条件查询, 需要在调用方法时传参数进来, 此

时, 可以在select标签中通过parameterType属性指定参数

的类型. 而在 SQL 语句中, 可以通过#{}的方式获取参数.

1.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();
}
}

1.2 多个参数的查询

多个参数传递时, 由于 sqlSession 中提供的查询方法只允许传入一个参数, 因此可以对多个参

数进行封装. 可以使用对象或 Map 集合.

1.2.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();
}
}

1.2.2 封装为 Map

xml文件书写:

<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();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值