万能map

用map前提:

        假设,我们的实例类,或者数据库中的表,字段或参数过多,我们应该考虑使用map!

接口

int addUser2(Map<String, Object> map);

mapper

    <insert id="addUser2" parameterType="map">
        insert into `user`(id, name, pwd) values (#{userId},#{userName},#{password})
    </insert>

 测试

  @Test
    public void addUser2() {
        SqlSession sqlSession = null;
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", 5);
            map.put("userName", "gt");
            map.put("password", "123456");

            sqlSession = MybatisUtils.getSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            int num = userMapper.addUser2(map);
            if (num > 0) {
                System.out.println("插入成功!");
            }
            sqlSession.commit();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

  • Map传递参数,直接在sql中取出key即可!【parameterType="map"】
  • 对象传递参数,直接在sql中取对象的属性即可!【parameterType="Object"】
  • 只有一个基本类型的情况下,可以直接在sql中取到!
  • 多个参数用Map,或者注解!

 输出结果:

 

扩展: 

模糊查询怎么写?

(1)java代码执行的时候,传递通配符%

List<User> userList = userMapper.getUserLike("%z%");

(2)在sql中拼接使用通配符 (不推荐,容易引起sql注入问题)

    <!--  select id, name, pwd from `user` where id = ?   -->
    <!--  select id, name, pwd from `user` where id = 1      一般情况-->
    <!--  select id, name, pwd from `user` where id = 1 or 1=1   sql注入情况-->
    <select id="getUserLike" resultType="com.gt.pojo.User" parameterType="string">
        select id, name, pwd from `user` where name like "%"#{value}"%"
    </select>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值