mybatis---parameterType参数传递

1. 只有一个参数时可以不写

User getUserById(int id);
<select id="getUserById" resultType="com.wy.bean.User">
    SELECT * FROM users WHERE id = #{id}
</select>
public void testGetUserById() {
    SqlSession session = MyBatisUtils.getSession();
    UserDao userDao = session.getMapper(UserDao.class);
    System.out.println(userDao.getUserById(2));
    MyBatisUtils.close(session);
}

2. 有多个参数时, parameterType不写

2.1 可以通过类对象进行传递

User getUsersByNameAndPassword(User user);
<select id="getUsersByNameAndPassword" resultType="com.wy.bean.User" >
    SELECT * FROM users WHERE username = #{username} AND PASSWORD = #{password}
</select>
public void testGetUsersByNameAndPassword() {
    SqlSession session = MyBatisUtils.getSession();
    UserDao userDao = session.getMapper(UserDao.class);
    User user = new User();
    user.setUsername("张三");
    user.setPassword("1000");
    System.out.println(userDao.getUsersByNameAndPassword(user));
    MyBatisUtils.close(session);
}

2.2 可以通过map进行传递

User getUserByNameAndPassword2(Map<String, Object> map);
<select id="getUserByNameAndPassword2" resultType="com.wy.bean.User">
    SELECT * FROM users WHERE username = #{username} AND PASSWORD = #{password}
</select>
public void testGetUserByNameAndPassword2() {
    SqlSession session = MyBatisUtils.getSession();
    UserDao userDao = session.getMapper(UserDao.class);
    Map<String, Object> map = new HashMap<>();
    map.put("username", "张三");
    map.put("password", "1000");
    System.out.println(userDao.getUserByNameAndPassword2(map));
    MyBatisUtils.close(session);
}

2.3 设置别名

void updateUserByNameAndPassword(@Param("username") String username, @Param("password") String password,  @Param("money") int money);
<update id="updateUserByNameAndPassword">
    UPDATE users SET money = #{money} WHERE username = #{username} AND PASSWORD = #{password}
</update>
public void testUpdateUserByNameAndPassword() {
    SqlSession session = MyBatisUtils.getSession();
    UserDao userDao = session.getMapper(UserDao.class);
    userDao.updateUserByNameAndPassword("张三", "1000", 18000);
    session.commit();
    MyBatisUtils.close(session);
}

2.4 直接获取参数列表中的参数

void updateUserByNameAndPassword2(String username, String password, int money);
<update id="updateUserByNameAndPassword2">
    UPDATE users SET money = #{arg2} WHERE username = #{arg0} AND PASSWORD = #{arg1}
</update>
public void testUpdateUserByNameAndPassword2() {
    SqlSession session = MyBatisUtils.getSession();
    UserDao userDao = session.getMapper(UserDao.class);
    userDao.updateUserByNameAndPassword2("张三", "1000", 38000);
    session.commit();
    MyBatisUtils.close(session);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值