美文网首页
Mybatis笔记

Mybatis笔记

作者: Mracale | 来源:发表于2020-07-22 09:41 被阅读0次

mybatis中最常用的Map参数传递

controller

@ApiOperation(value = "多个参数查询")
@GetMapping("findByMapParams")
public ResultMsg findByMapParams(Short gender,String age)
{
    Map params = new HashMap<>();
    params.put("gender",gender);
    params.put("age",age);
    List result= employeeMapper.selectByMapParams(params);
    return ResultMsg.getMsg(result);
}

mapper

List<Employee> selectByMapParams(Map params);

可以看到使用map来传递多个参数,可以直接使用参数名称进行引用

<select id="selectByMapParams" resultMap="BaseResultMap" parameterType="map">
  select * from employee where gender = #{gender} and age = #{age}
</select>

Mybatis 中$与#的区别

1 #是将传入的值当做\color{red}{字符串}的形式,eg:select id,name,age from student where id =#{id},当前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id ='1'.

2 是将传入的数据直接显示生成sql语句,eg:select id,name,age from student where id ={id},当前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id = 1.

3 使用#可以很大程度上防止sql注入。(语句的拼接)

4 但是如果使用在order by 中就需要使用 $.

5 在大多数情况下还是经常使用#,但在不同情况下必须使用$.

我觉得#与的区别最大在于:#{} 传入值时,sql解析时,参数是带引号的,而的区别最大在于:#{} 传入值时,sql解析时,参数是带引号的,而{}穿入值,sql解析时,参数是不带引号的。

一 : 理解mybatis中 $与#

在mybatis中的$与#都是在sql中动态的传入参数。

eg:select id,name,age from student where name=#{name}  这个name是动态的,可变的。当你传入什么样的值,就会根据你传入的值执行sql语句。

二:使用$与#

{}: 解析为一个 JDBC 预编译语句(prepared statement)的参数标记符,一个 #{ } 被解析为一个参数占位符 。

${}: 仅仅为一个纯碎的 string 替换,在动态 SQL 解析阶段将会进行变量替换。

name-->cy

eg: select id,name,age from student where name=#{name} -- name='cy'

   select id,name,age from student where name=${name}    -- name=cy

MyBatis+MySQL 返回插入的主键ID

方法:在mapper中指定keyProperty属性,示例如下:
xml

<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User">  
    insert into user(userName,password,comment)  
    values(#{userName},#{password},#{comment})  
</insert>  

如上所示,我们在insert中指定了keyProperty="userId",其中userId代表插入的User对象的主键属性。

相关文章

  • Spring系列 | 小荷才露尖尖角

    MyBatis学习笔记 MyBatis操练 MyBatis源码 SpringMVC学习笔记 SpringMVC...

  • MyBatis缓存

    MyBatis Mybatis笔记连载上篇连接Mybatis简单操作学习 Mybatis笔记连载下篇连接Mybat...

  • Mybatis动态SQL

    MyBatis Mybatis笔记连载上篇连接MyBatis缓存Mybatis笔记连载下篇连接 动态SQL 动态S...

  • Mybatis 学习笔记

    Mybatis 学习笔记 配置 MyBatis 环境 导入MyBaits依赖jar包 要使用 MyBatis, 需...

  • Mybatis学习笔记汇总(包括源码和jar包)

    博客整理 Mybatis学习笔记(一)——对原生jdbc中问题的总结 Mybatis学习笔记(二)——Mybati...

  • Mybatis笔记 一

    Mybatis笔记 一 为什么学Mybatis 目前最主流的持久层框架为hibernate与mybatis,而且国...

  • Mybatis--day01

    非本人总结的笔记,抄点笔记复习复习。感谢传智博客及黑马程序猿成长 什么是Mybatis ​ MyBatis 本...

  • 一,MyBatis应用分析与实践

    之前学习MyBatis整理了一些笔记,笔记分为四个部分:1.MyBatis应用分析与实践[https://www....

  • 初识MyBatis

    MyBatis学习笔记(一) 1、什么是MyBatis2、安装3、第一个mybatis实例 前言 1、ORM:Ob...

  • Spring和MyBatis整合笔记

    对于 Spring 框架和 MyBatis 框架整合,摸爬滚打总结了这篇笔记,MyBatis 用 XML 文件替代...

网友评论

      本文标题:Mybatis笔记

      本文链接:https://www.haomeiwen.com/subject/wgfzkktx.html