当前位置: 首页 > news >正文

Mybatis之参数处理

  在MyBatis中,参数处理是非常关键的部分,它负责将传入的参数正确映射到SQL语句中 

单个简单类型参数

简单类型对于mybatis来说都是可以自动类型识别的:

  • 也就是说对于mybatis来说,它是可以自动推断出ps.setXxxx()方法的。ps.setString()还是ps.setInt()。它可以自动推断。

简单类型包括:

  • byte short int long float double char

  • Byte Short Integer Long Float Double Character

  • String

  • java.util.Date

  • java.sql.Date

参数自动绑定
在执行 SQL 时,MyBatis 会根据参数的类型自动绑定到 PreparedStatement 对应的 setXxx() 方法。
示例:

public interface UserMapper {User getUserById(int id);
}

SQL 映射文件:

<select id="getUserById" resultType="User">SELECT * FROM user WHERE id = #{id}
</select>

在执行时,MyBatis 自动判断 idint 类型,因此会使用 PreparedStatement.setInt() 方法。

多个参数处理(使用@Param注解)

如果一个方法有多个参数,你可以使用 @Param 注解给参数命名,方便在 SQL 中引用:

示例:

   /*** 根据name和age查询* @param name* @param age* @return*/List<Student> selectByNameAndAge(@Param(value="name") String name, @Param("age") int age);

 value值可以省略不写

SQL映射文件:

    <select id="selectByNameAndAge" resultType="student">select * from t_student where name = #{name} and age = #{age}</select>

Java对象作为参数

查找:

你也可以将 Java 的对象传递给 MyBatis 方法,MyBatis 会自动将对象的属性与 SQL 中的字段进行映射:

public interface UserMapper {User getUserByObject(User user);
}

SQL映射文件:

<select id="getUserByObject" resultType="User">SELECT * FROM user WHERE name = #{name} AND age = #{age}
</select>

这里 #{name}#{age} 会自动对应 User 对象中的 nameage 属性。

使用pojo类保存数据 :

/*** 保存学生数据* @param student 实体类pojo* @return*/int insertPojo(Student student);

sql映射文件:

<!--    pojo#{}里面写的是属性名--><insert id="insertPojo" parameterType="mybatis.pojo.Student">insert into t_student (id, name, age, sex, birth, height)values (#{id}, #{name}, #{age}, #{sex}, #{birth}, #{height})</insert>

 测试类:

 @Testpublic void testInsertPojo(){Student student = new Student("小李子",23,1.67,new Date(),'男');SqlSession sqlSession = SqlSessionUtil.openSession();StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);mapper.insertPojo(student);sqlSession.commit();sqlSession.close();}

易错:

注意这里我的student类中存在不含有id的构造方式(也就是构造方式的重载),因为我id设置了自增主键,所以可以不需要指定id值,这里不能传入null会报错!!! 

Map 作为参数 

查找 

/**
* 根据name和age查询
* @param paramMap
* @return
*/
List<Student> selectByParamMap(Map<String,Object> paramMap);

测试类: 

@Test
public void testSelectByParamMap(){// 准备MapMap<String,Object> paramMap = new HashMap<>();paramMap.put("nameKey", "张三");paramMap.put("ageKey", 20);List<Student> students = mapper.selectByParamMap(paramMap);students.forEach(student -> System.out.println(student));
}

sql映射文件:

<select id="selectByParamMap" resultType="student">select * from t_student where name = #{nameKey} and age = #{ageKey}
</select>

这种方式是手动封装Map集合,将每个条件以key和value的形式存放到集合中。然后在使用的时候通过#{map集合的key}来取值。

通过map来保存数据到表格中

  /*** 保存学生数据* @param paramMap 使用map进行传参*/void insertStudent(Map<String, Object> paramMap);

 sql映射文件:

<!--这里设置自增主键(创建表格时也需要声明是自增主键),id值就可以传null值了,否则会报错--><insert id="insertStudent" parameterType="map" useGeneratedKeys="true" keyProperty="id">insert into t_student (id, name, age, sex, birth, height)values (null,#{name}, #{age}, #{sex}, #{birth}, #{height})</insert>

java测试类: 

    public void testInsertMapParam() {// 准备 MapMap<String, Object> paramMap = new HashMap<>();paramMap.put("name", "张三");paramMap.put("age", 20);paramMap.put("sex", '女'); paramMap.put("birth", new java.sql.Date(new Date().getTime()));  // 使用 java.sql.DateparamMap.put("height", 1.85);SqlSession sqlSession = SqlSessionUtil.openSession();StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);mapper.insertStudent(paramMap);sqlSession.commit();sqlSession.close();}

易错点:

如果不设置自增主键而且sql映射文件上面id值为null就会报错!!所以一定要记得设置自增主键

http://www.lryc.cn/news/468493.html

相关文章:

  • windows内核探索--打印windows的GDT表(全局描述符表)
  • 【ChatGPT】让ChatGPT帮助进行头脑风暴与创意生成
  • 大数据处理随堂测试
  • 2024最新pycharm安装教程及基本使用(超详细,新手小白必看)
  • 三国杀钓鱼自动化
  • 在pycharm中使用sqllite
  • Linux——文件操作
  • 数据结构 ——— 数组栈oj题:有效括号
  • Character AI被起诉!14岁青少年自杀,AI陪伴何去何从
  • CSS3 动画相关属性实例大全(三)(columns、filter、flex、flex-basis 、flex-grow、flex-shrink属性)
  • 中国最厉害的思想家改名大师颜廷利:以诚信为基,塑企业信誉
  • Python 代码实现用于进行水质模拟和优化加氯量
  • 挖矿病毒来势汹汹
  • 国产数据库的蓝海在哪?
  • MySQL~表的操作(创建表,查看表,修改表,删除表)
  • 多线程加锁与手搓智能指针实践
  • 3180. 执行操作可获得的最大总奖励 I
  • react18中的jsx 底层渲染机制相关原理
  • Spring Boot 实现文件上传下载功能
  • ArcGIS 10.8 安装教程(含安装包)
  • 【小白学机器学习16】 概率论的世界观2: 从正态分布去认识世界
  • Python 爬虫项目实战:爬取某云热歌榜歌曲
  • HCIP-HarmonyOS Application Developer 习题(十八)
  • 操作系统学习笔记2.3互斥
  • LLM - 使用 Neo4j 可视化 GraphRAG 构建的 知识图谱(KG) 教程
  • Linux 环境的搭建方式->远程登录->免密登录
  • react18中的计算属性及useMemo的性能优化技巧
  • Python 实现高效的 SM4 大文件加密解密实战指南20241024
  • 数据结构~红黑树
  • 【ROS GitHub使用】