【持续更新】Mybatis常用代码汇总

目录

通用

[#{} 和 {}](#{} 和 {})

返回类型

查询

sql处理

in数组处理

if语句

[choose when](#choose when)

[association 一对一关联查询](#association 一对一关联查询)

日期格式


通用

#{} 和 ${}

在MyBatis 的xml映射配置文件中,动态传参有#{}和${}两种方式

1)#{}:动态解析 -> 预编译 -> 执行

2)${}:动态解析 -> 编译 -> 执行

1)变量替换后,#{} 对应的变量自动加上单引号 ''

2)变量替换后,${} 对应的变量不会加上单引号 ''

1)#{} 能防止sql 注入

2)${} 不能防止sql 注入

使用方式相同

(1)public User getUser(String username,String password);

<select id="getUser" resultType="com.User">select * from t user where username=#{arg0} and password=#{arg1}>

</select>

(2)使用自定义参数名,前提: 在映射器接口方法的参数前加注解@Param("")

public User getUser(@Param("username") String username,@Param("password") String password);

或 public User getUser(User user);

<select id="getUser" resultType="com.User">select * from t user where username=#{username} and password=#{password} </select>

返回类型

1.实体类: 将查询结果封装为Java对象,通常是自定义的实体类

2.Map: 将查询结果封装为Map对象

3.List: 将查询结果封装为List对象。

4.Array: 将查询结果封装为数组对象

5.ResultMap: 将查询结果封装为ResultMap对象

6.自定义类型外理器:根据自定义类型的类或数据类型外理查询结果,将查询结果封装为自定义类型的对象

7.Void: 不返回任何结果。

8.Cursor: 返回结果集的游标,可以逐行读取结果集

9.InputStream: 返回结果集的二进制流,适合处理较大的结果集

查询

sql处理

in数组处理

<if test="bankids !=null and bankids.size()>0" >

and (t.BANKID IN

<foreach item="item" collection="bankids" open="(" close=")" index="index">

<if test="index != 0">

<choose>

<when test="index % 1000 == 999">) OR t.BANKID IN(</when>

<otherwise>,</otherwise>

</choose>

</if>

#{item}

</foreach>)

</if>

if语句

<if test="startdate !=null">

AND t.TRANDATE &gt;= to_date(#{startdate},'yyyy-MM-dd HH24:mi:ss')

</if>

choose when

<choose>

<when test="index % 1000 == 999">) OR t.FILLINFOSTATE IN(</when>

<otherwise>,</otherwise>

</choose>

association 一对一关联查询

<association property="customer" javaType="Customer"

select="com.xu.mapper.CustomerMapper.selectById"

column="{id:customer_id}">

</association>

日期格式

and t.trandate <!CDATA\[\>=]> to_date(#{startDate},'yyyy-MM-dd')

相关推荐
EatFan4 小时前
Spring Boot 4 落地观察:从 yudao-cloud、matecloud、JPower 看国产脚手架的升级路线与迁移清单
java·spring boot·后端·spring cloud·微服务·后端开发·jdk 21
Maiko Star5 小时前
* LangChain 提示词模板详解:ChatPromptTemplate 的使用与高级特性
java·人工智能·langchain
段一凡-华北理工大学5 小时前
大模型应用开发 100 天:Python + LLM 从入门到精通 day26~Prompt 调试与优化——A/B 测试与效果评估
windows·python·大模型·prompt·智能体·提示词工程·高炉智能化
fox_charon6 小时前
Windows 下 CLI 参数的引号陷阱:为什么 --resume 'uuid' 会失败
windows·shell·cmd·cli·引号
现任明教教主~7 小时前
Thinkphp站群蜘蛛池SaaS系统YanyvSEO含多用户/积分/六大引擎计费/易支付对接
java·开发语言·spring
一条破秋裤7 小时前
Linux 线程创建:pthread_create 与基本回收
java·linux·运维
染指11107 小时前
128.Agent-LangChain核心组件-中间件-调用模型的时候
人工智能·windows·中间件·langchain·agent
布吉岛的石头8 小时前
Java 程序员第 49 阶段5:BERT 预训练目标 MLM+NSP 的工程含义
java·人工智能·深度学习·bert·transformer
Frag0ut8 小时前
Chrome与Chromium内核浏览器在Windows 11上的新特性全景解析
前端·chrome·windows·web安全·chromium·gemini ai·playready drm
摇滚侠8 小时前
《On Java 中文版 基础卷》阅读笔记 对象无处不在 03
java·笔记·python