mybatis动态SQL语句

本文详细介绍了MyBatis框架中动态SQL的多种用法,包括if、where、set、trim、choose及foreach标签的应用场景与注意事项,帮助开发者更好地理解和运用这些特性。

有些时候,sql语句where条件中,需要一些安全判断,例如按性别检索,如果传入的参数是空的,此时查询出的结果很可能是空的,也许我们需要参数为空时,是查出全部的信息。这是我们可以使用动态sql,增加一个判断,当参数不符合要求的时候,我们可以不去判断此查询条件。
        下文均采用mysql语法和函数(例如字符串链接函数CONCAT)。

3.1 if标签

 一个很普通的查询:
 


Xml代码 
 1.<!-- 查询学生list,like姓名 --> 
 2.<select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap"> 
 3.    SELECT * from STUDENT_TBL ST   
 4.WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
 5.</select> 
 

但是此时如果studentName是null或空字符串,此语句很可能报错或查询结果为空。此时我们使用if动态sql语句先进行判断,如果值为null或等于空字符串,我们就不进行此条件的判断。
 
修改为:
 


Xml代码 
 1.<!-- 查询学生list,like姓名 --> 
 2.<select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap"> 
 3.    SELECT * from STUDENT_TBL ST  
 4.    <if test="studentName!=null and studentName!='' "> 
 5.        WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
 6.    </if> 
 7.</select> 
 
 此时,当studentName的值为null或’’的时候,我们并不进行where条件的判断,所以当studentName值为null或’’值,不附带这个条件,所以查询结果是全部。
 
 由于参数是Java的实体类,所以我们可以把所有条件都附加上,使用时比较灵活, new一个这样的实体类,我们需要限制那个条件,只需要附上相应的值就会where这个条件,相反不去赋值就可以不在where中判断。
 

   代码中的where标签,请参考3.2.1.
 


Xml代码 
 1.<!-- 查询学生list,like姓名,=性别、=生日、=班级,使用where,参数entity类型 --> 
 2.<select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap"> 
 3.    SELECT * from STUDENT_TBL ST  
 4.    <where> 
 5.        <if test="studentName!=null and studentName!='' "> 
 6.            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
 7.        </if> 
 8.        <if test="studentSex!= null and studentSex!= '' "> 
 9.            AND ST.STUDENT_SEX = #{studentSex}  
 10.        </if> 
 11.        <if test="studentBirthday!=null"> 
 12.            AND ST.STUDENT_BIRTHDAY = #{studentBirthday}  
 13.        </if> 
 14.        <if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' "> 
 15.            AND ST.CLASS_ID = #{classEntity.classID}  
 16.        </if> 
 17.    </where> 
 18.</select> 
 
查询,姓名中有‘李’,男,生日在‘1985-05-28’,班级在‘20000002’的学生。
 


Java代码 
 1.StudentEntity entity = new StudentEntity();  
 2.entity.setStudentName("李");  
 3.entity.setStudentSex("男");  
 4.entity.setStudentBirthday(StringUtil.parse("1985-05-28"));  
 5.entity.setClassEntity(classMapper.getClassByID("20000002"));  
 6.List<StudentEntity> studentList = studentMapper.getStudentListWhereEntity(entity);  
 7.for( StudentEntity entityTemp : studentList){  
 8.    System.out.println(entityTemp.toString());  
 9.} 
 

3.2 where、set、trim标签
 

3.2.1 where
 
当if标签较多时,这样的组合可能会导致错误。例如,like姓名,等于指定性别等:
 


Xml代码 
 1.<!-- 查询学生list,like姓名,=性别 --> 
 2.<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap"> 
 3.    SELECT * from STUDENT_TBL ST  
 4.        WHERE  
 5.        <if test="studentName!=null and studentName!='' "> 
 6.            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
 7.        </if> 
 8.        <if test="studentSex!= null and studentSex!= '' "> 
 9.            AND ST.STUDENT_SEX = #{studentSex}  
 10.        </if> 
 11.</select> 
 
 如果上面例子,参数studentName为null或’’,则或导致此sql组合成“WHERE AND”之类的关键字多余的错误SQL。
 这时我们可以使用where动态语句来解决。这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。
 上面例子修改为:
 


Xml代码 
 1.<!-- 查询学生list,like姓名,=性别 --> 
 2.<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap"> 
 3.    SELECT * from STUDENT_TBL ST  
 4.    <where> 
 5.        <if test="studentName!=null and studentName!='' "> 
 6.            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
 7.        </if> 
 8.        <if test="studentSex!= null and studentSex!= '' "> 
 9.            AND ST.STUDENT_SEX = #{studentSex}  
 10.        </if> 
 11.    </where> 
 12.</select> 
 

3.2.2 set
 
当在update语句中使用if标签时,如果前面的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号。
没有使用if标签时,如果有一个参数为null,都会导致错误,如下示例:
 


Xml代码 
 1.<!-- 更新学生信息 --> 
 2.<update id="updateStudent" parameterType="StudentEntity"> 
 3.    UPDATE STUDENT_TBL  
 4.       SET STUDENT_TBL.STUDENT_NAME = #{studentName},  
 5.           STUDENT_TBL.STUDENT_SEX = #{studentSex},  
 6.           STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
 7.           STUDENT_TBL.CLASS_ID = #{classEntity.classID}  
 8.     WHERE STUDENT_TBL.STUDENT_ID = #{studentID};  
 9.</update> 
 

 使用set+if标签修改后,如果某项为null则不进行更新,而是保持数据库原值。如下示例:
 


Xml代码 
 1.<!-- 更新学生信息 --> 
 2.<update id="updateStudent" parameterType="StudentEntity"> 
 3.    UPDATE STUDENT_TBL  
 4.    <set> 
 5.        <if test="studentName!=null and studentName!='' "> 
 6.            STUDENT_TBL.STUDENT_NAME = #{studentName},  
 7.        </if> 
 8.        <if test="studentSex!=null and studentSex!='' "> 
 9.            STUDENT_TBL.STUDENT_SEX = #{studentSex},  
 10.        </if> 
 11.        <if test="studentBirthday!=null "> 
 12.            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
 13.        </if> 
 14.        <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' "> 
 15.            STUDENT_TBL.CLASS_ID = #{classEntity.classID}  
 16.        </if> 
 17.    </set> 
 18.    WHERE STUDENT_TBL.STUDENT_ID = #{studentID};  
 19.</update> 
 
3.2.3 trim
 
 trim是更灵活的去处多余关键字的标签,他可以实践where和set的效果。
 

 where例子的等效trim语句:
 


Xml代码 
 1.<!-- 查询学生list,like姓名,=性别 --> 
 2.<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap"> 
3.    SELECT * from STUDENT_TBL ST  
 4.    <trim prefix="WHERE" prefixOverrides="AND|OR"> 
 5.        <if test="studentName!=null and studentName!='' "> 
 6.            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
 7.        </if> 
 8.        <if test="studentSex!= null and studentSex!= '' "> 
 9.            AND ST.STUDENT_SEX = #{studentSex}  
 10.        </if> 
 11.    </trim> 
 12.</select> 
 
set例子的等效trim语句:
 


Xml代码 
 1.<!-- 更新学生信息 --> 
 2.<update id="updateStudent" parameterType="StudentEntity"> 
 3.    UPDATE STUDENT_TBL  
 4.    <trim prefix="SET" suffixOverrides=","> 
 5.        <if test="studentName!=null and studentName!='' "> 
 6.            STUDENT_TBL.STUDENT_NAME = #{studentName},  
 7.        </if> 
 8.        <if test="studentSex!=null and studentSex!='' "> 
 9.            STUDENT_TBL.STUDENT_SEX = #{studentSex},  
 10.        </if> 
 11.        <if test="studentBirthday!=null "> 
 12.            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
 13.        </if> 
 14.        <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' "> 
 15.            STUDENT_TBL.CLASS_ID = #{classEntity.classID}  
 16.        </if> 
 17.    </trim> 
 18.    WHERE STUDENT_TBL.STUDENT_ID = #{studentID};  
 19.</update> 
 

3.3 choose (when, otherwise)
 
         有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis提供了choose 元素,按顺序判断when中的条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。
         if是与(and)的关系,而choose是或(or)的关系。
 

         例如下面例子,同样把所有可以限制的条件都写上,方面使用。选择条件顺序,when标签的从上到下的书写顺序:
 


Xml代码 
 1.<!-- 查询学生list,like姓名、或=性别、或=生日、或=班级,使用choose --> 
 2.<select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap"> 
 3.    SELECT * from STUDENT_TBL ST  
 4.    <where> 
 5.        <choose> 
 6.            <when test="studentName!=null and studentName!='' "> 
 7.                    ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
 8.            </when> 
 9.            <when test="studentSex!= null and studentSex!= '' "> 
 10.                    AND ST.STUDENT_SEX = #{studentSex}  
 11.            </when> 
 12.            <when test="studentBirthday!=null"> 
 13.                AND ST.STUDENT_BIRTHDAY = #{studentBirthday}  
 14.            </when> 
 15.            <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' "> 
 16.                AND ST.CLASS_ID = #{classEntity.classID}  
 17.            </when> 
 18.            <otherwise> 
 19.                  
 20.            </otherwise> 
 21.        </choose> 
 22.    </where> 
 23.</select> 
 
3.4 foreach
 
对于动态SQL 非常必须的,主是要迭代一个集合,通常是用于IN 条件。
List 实例将使用“list”做为键,数组实例以“array” 做为键。
 
 
 
 3.4.1参数为list实例的写法:
 
SQL写法:
 


Xml代码 
 1.<select id="getStudentListByClassIDs" resultMap="studentResultMap"> 
 2.    SELECT * FROM STUDENT_TBL ST  
 3.     WHERE ST.CLASS_ID IN   
 4.     <foreach collection="list" item="classList"  open="(" separator="," close=")"> 
 5.        #{classList}  
 6.     </foreach>     
 7.</select> 
 
接口的方法声明:
 


Java代码 
 1.public List<StudentEntity> getStudentListByClassIDs(List<String> classList); 
 
 测试代码,查询学生中,在20000002、20000003这两个班级的学生:
 


Java代码 
 1.List<String> classList = new ArrayList<String>();  
 2.classList.add("20000002");  
 3.classList.add("20000003");  
 4. 
 5.List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(classList);  
 6.for( StudentEntity entityTemp : studentList){  
 7.    System.out.println(entityTemp.toString());  
 8.} 
 

 3.4.2参数为Array实例的写法:

SQL语句:
 


Xml代码 
 1.<select id="getStudentListByClassIDs" resultMap="studentResultMap"> 
 2.    SELECT * FROM STUDENT_TBL ST  
 3.     WHERE ST.CLASS_ID IN   
 4.     <foreach collection="array" item="ids"  open="(" separator="," close=")"> 
 5.        #{ids}  
 6.     </foreach> 
 7.</select> 
 

 接口的方法声明:
 


Java代码 
 1.public List<StudentEntity> getStudentListByClassIDs(String[] ids); 
 
测试代码,查询学生中,在20000002、20000003这两个班级的学生:
 


Java代码 
 1.String[] ids = new String[2];  
 2.ids[0] = "20000002";  
 3.ids[1] = "20000003";  
 4.List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(ids);  
 5.for( StudentEntity entityTemp : studentList){  
 6.    System.out.println(entityTemp.toString());  
 7.} 


本文来自优快云博客:http://blog.youkuaiyun.com/ask_rent/archive/2011/04/13/6320326.aspx

内容概要:本文详细介绍了一个基于Java和Vue的联邦学习隐私保护推荐系统的设计与实现。系统采用联邦学习架构,使用户数据在本地完成模型训练,仅上传加密后的模型参数或梯度,通过中心服务器进行联邦平均聚合,从而实现数据隐私保护与协同建模的双重目标。项目涵盖完整的系统架构设计,包括本地模型训练、中心参数聚合、安全通信、前后端解耦、推荐算法插件化等模块,并结合差分隐私与同态加密等技术强化安全性。同时,系统通过Vue前端实现用户行为采集与个性化推荐展示,Java后端支撑高并发服务与日志处理,形成“本地训练—参数上传—全局聚合—模型下发—个性化微调”的完整闭环。文中还提供了关键模块的代码示例,如特征提取、模型聚合、加密上传等,增强了项目的可实施性与工程参考价值。 适合人群:具备一定Java和Vue开发基础,熟悉Spring Boot、RESTful API、分布式系统或机器学习相关技术,从事推荐系统、隐私计算或全栈开发方向的研发人员。 使用场景及目标:①学习联邦学习在推荐系统中的工程落地方法;②掌握隐私保护机制(如加密传输、差分隐私)与模型聚合技术的集成;③构建高安全、可扩展的分布式推荐系统原型;④实现前后端协同的个性化推荐闭环系统。 阅读建议:建议结合代码示例深入理解联邦学习流程,重点关注本地训练与全局聚合的协同逻辑,同时可基于项目架构进行算法替换与功能扩展,适用于科研验证与工业级系统原型开发。
源码来自:https://pan.quark.cn/s/a4b39357ea24 遗传算法 - 简书 遗传算法的理论是根据达尔文进化论而设计出来的算法: 人类是朝着好的方向(最优解)进化,进化过程中,会自动选择优良基因,淘汰劣等基因。 遗传算法(英语:genetic algorithm (GA) )是计算数学中用于解决最佳化的搜索算法,是进化算法的一种。 进化算法最初是借鉴了进化生物学中的一些现象而发展起来的,这些现象包括遗传、突变、自然选择、杂交等。 搜索算法的共同特征为: 首先组成一组候选解 依据某些适应性条件测算这些候选解的适应度 根据适应度保留某些候选解,放弃其他候选解 对保留的候选解进行某些操作,生成新的候选解 遗传算法流程 遗传算法的一般步骤 my_fitness函数 评估每条染色体所对应个体的适应度 升序排列适应度评估值,选出 前 parent_number 个 个体作为 待选 parent 种群(适应度函数的值越小越好) 从 待选 parent 种群 中随机选择 2 个个体作为父方和母方。 抽取父母双方的染色体,进行交叉,产生 2 个子代。 (交叉概率) 对子代(parent + 生成的 child)的染色体进行变异。 (变异概率) 重复3,4,5步骤,直到新种群(parentnumber + childnumber)的产生。 循环以上步骤直至找到满意的解。 名词解释 交叉概率:两个个体进行交配的概率。 例如,交配概率为0.8,则80%的“夫妻”会生育后代。 变异概率:所有的基因中发生变异的占总体的比例。 GA函数 适应度函数 适应度函数由解决的问题决定。 举一个平方和的例子。 简单的平方和问题 求函数的最小值,其中每个变量的取值区间都是 [-1, ...
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值