详细聊聊Mybatis中万能的Map

网友投稿 886 2022-11-16

详细聊聊Mybatis中万能的Map

详细聊聊Mybatis中万能的Map

目录万能的Mapdemomap 实现add usermap 实现通过id查询多个参数可以使用Map进行传参总结

万能的Map

假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们需要考虑使用Map

简单来说,map你用什么参数就写什么参数,而实体类需要写所有参数。

map不需要名称完全对应,通过键的映射取值,实体类必须要求和实体类中属性名字一样

map传递参数,直接在sql中取出key即可 【parameterType=“map”】

对象传递参数,直接在sql中取对象的属性即可 【parameterType=“Object”】

http://

只有一个基本类型 (如int),可以直接在sql中找到

多个参数用Map或者注解

demo

map 实现add user

UserMapper接口

public interface UserMapper {

User getUserById2(Map map);

}

UserMaper.xml

insert into mybatis.user(id, name, pwd) VALUES (#{userid},#{username},#{password});

test

@Test

public void addUser2(){

SqlSession sqlSession=MybatisUtils.getSqlSession();

UserMapper mapper=sqlSession.getMapper(UserMapper.class);

Map map=new HashMap();

map.put("userid",5);

map.put("username","王五");

map.put("password","23333");

mapper.addUser2(map);

sqlSession.commit();

sqlSession.close();

}

map 实现通过id查询

UserMapper接口

public interface UserMapper {

User getUserById2(Map map);

}

UserMaper.xml

select * from mybatis.user where id=#{id} and name=#{name}

test

@Test

public void getUserById2() {

Sqlhttp://Session sqlSession = MybatisUtils.getSqlSession();

UserMapper mapper = sqlSession.getMapper(UserMapper.class);

Map map=new HashMap();

map.put("id",1);

map.put("name","冷丁");

User userById = mapper.getUserById2(map);

System.out.println(userById);

sqlSession.close();

}

多个参数可以使用Map进行传参

xml文件SQL语句

select * from t_goods

where

current_price between #{min} and #{max}

order by current_price

limit 0,#{limt}

总结

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Filebeat收集Nginx日志
下一篇:深入理解 Golang 中的 new 和 make 是什么, 差异在哪?
相关文章

 发表评论

暂时没有评论,来抢沙发吧~