Mybatis4_动态SQL

蚂蚁开源LingBot-World 2.0:开箱即用的世界模型推理引擎实践指南 世界模型作为AI从感知迈向决策的关键技术,其核心原理是通过模拟与预测,让智能体能在执行动作前预演结果,实现从被动反应到主动规划的跨越。这一技术价值在于大幅降低了复杂AI Agent的决策逻辑开发难度,使智能体能够进行因果推理和长链条规划。在应用场景上,世界模型广泛应用于游戏NPC自主决策、机器人任务规划、业务流程模拟推演等需要多步骤、有状态任务执行的领域。本文以蚂蚁集团开源的LingBot-World 2.0为例,深入解析这一面向具身智能和复杂任务规划的推理引擎,通过一个完整的网格世界寻路示例,展示如何将其 阅读详情

MyBatis 动态SQL

  • 动态 SQL是MyBatis强大特性之一。极大的简化我们拼装SQL的操作。
  • 动态 SQL 元素和使用 JSTL 或其他类似基于 XML 的文本处理器相似。
  • MyBatis 采用功能强大的基于 OGNL 的表达式来简化操作。

1. if

<!--
	 if:判断。
	 choose (when, otherwise):分支选择,带了break的swtich-case如果带了id就用id查,
	 如果带了lastName就用lastName查,只会进入其中一个。
	 trim:字符串截取(where(封装查询条件),set(封装修改条件))。
	 foreach:遍历集合。
-->
<!-- 查询员工,要求携带了哪个字段查询条件就带上这个字段的值。 -->
<!-- public List<Employee> getEmpsByConditionIf(Employee employee); -->
<select id="getEmpsByConditionIf" resultType="com.ginger.mybatis.bean.Employee">
	select * from employee where
	<!--
		test:判断表达式(OGNL)OGNL参照PPT或者官方文档,类似于Java中JSTL表达式的 c:if  test,
		从参数中取值进行判断,遇见特殊符号应该去写转义字符不然会报错:&&(&amp;&amp;)''(&quot;&quot;)。
	-->
	<if test="id!=null">
		id=#{id}
	</if>
	<if test="lastName!=null &amp;&amp; lastName!=&quot;&quot;">
		and last_name like #{lastName}
	</if>
	<if test="email!=null and email.trim()!=&quot;&quot;">
		and email=#{email}
	</if>
	<!-- gender 类型是字符串为什么不出错呢?ognl会进行字符串与数字的转换判断  "0"==0 -->
	<if test="gender==0 or gender==1">
		and gender=#{gender}
	</if>
</select>
// 接口
public List<Employee> getEmpsByConditionIf(Employee employee);
// 测试
@Test
public void testDynamicSql() throws IOException{
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try{
       EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        //select * from tbl_employee where id=? and last_name like ?
        Employee employee = new Employee(1, "小明", null, null);
	    List<Employee> emps = mapper.getEmpsByConditionIf(employee );
		for (Employee emp : emps) {
			System.out.println(emp);
		}
    }finally{
        openSession.close();
    }
}

在这里插入图片描述

2. choose (when, otherwise)

<!-- public List<Employee> getEmpsByConditionChoose(Employee employee); -->
<select id="getEmpsByConditionChoose" resultType="com.ginger.mybatis.bean.Employee">
	select * from employee where
	<!-- 如果带了id就用id查,如果带了lastName就用lastName查,只会进入其中一个 -->
	<choose>
		<when test="id!=null">
			id=#{id}
		</when>
		<when test="lastName!=null">
			last_name like #{lastName}
		</when>
		<when test="email!=null">
			email = #{email}
		</when>
		<otherwise>
			gender = 0
		</otherwise>
	</choose>
</select>
//接口
public List<Employee> getEmpsByConditionChoose(Employee employee);
// 测试
@Test
public void testDynamicSql01() throws IOException{
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try{
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);

        Employee employee = new Employee(2, "小王", null, null);
        List<Employee> emps = mapper.getEmpsByConditionChoose(employee);
        for (Employee emp : emps) {
            System.out.println(emp);
        }
    }finally{
        openSession.close();
    }
}

在这里插入图片描述

3. trim (where, set)

3.1 where

演示一个sql拼接的问题。

<!-- public List<Employee> getEmpsByConditionIf(Employee employee); -->
<select id="getEmpsByConditionIf" resultType="com.ginger.mybatis.bean.Employee">
	select * from employee 
	where 
	<if test="id!=null">
		id=#{id}	<!-- 这里如果不传递参数 sql 语法会出错。 -->
	</if>
	<if test="lastName!=null &amp;&amp; lastName!=&quot;&quot;">
		and last_name like #{lastName}
	</if>
	<if test="email!=null and email.trim()!=&quot;&quot;">
		and email=#{email}
	</if>
	<!-- gender 类型是字符串为什么不出错呢?ognl会进行字符串与数字的转换判断  "0"==0 -->
	<if test="gender==0 or gender==1">
		and gender=#{gender}
	</if>
</select>
// 接口
public List<Employee> getEmpsByConditionIf(Employee employee);
// 测试
@Test
public void testDynamicSql() throws IOException{
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try{
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        Employee employee = new Employee(null, "小明", null, null);
		List<Employee> emps = mapper.getEmpsByConditionIf(employee );
		for (Employee emp : emps) {
			System.out.println(emp);
		}
    }finally{
        openSession.close();
    }
}

在这里插入图片描述

上面的语法报错一般是有两种办法解决。
查询的时候如果某些条件没带可能sql拼装会有问题

  • 给 where 后面加上1=1,以后的条件都and xxx。
  • mybatis 使用 where 标签来将所有的查询条件包括在内,mybatis就会将where标签中拼装的sql,多出来的 and 或者 or 去掉。
    注意:where只会去掉第一个多出来的and或者or,如果and或者or出现在id = #{id} 后面where就不起作用了。

方式1

<!-- public List<Employee> getEmpsByConditionIf(Employee employee); -->
<select id="getEmpsByConditionIf" resultType="com.ginger.mybatis.bean.Employee">
	select * from employee 
	where 1=1	<!-- 加上 1=1--> 
	<if test="id!=null">
		and id=#{id}	<!-- 在这里加上 and -->  
	</if>
	<if test="lastName!=null &amp;&amp; lastName!=&quot;&quot;">
		and last_name like #{lastName}
	</if>
	<if test="email!=null and email.trim()!=&quot;&quot;">
		and email=#{email}
	</if>
	<!-- gender 类型是字符串为什么不出错呢?ognl会进行字符串与数字的转换判断  "0"==0 -->
	<if test="gender==0 or gender==1">
		and gender=#{gender}
	</if>
</select>

方式2

<!-- public List<Employee> getEmpsByConditionIf(Employee employee); -->
<select id="getEmpsByConditionIf" resultType="com.ginger.mybatis.bean.Employee">
	select * from employee
	<!-- where -->
	<where>  <!-- 使用 Mybatis 自带的 where 标签 -->
		<if test="id!=null">
			id=#{id}
		</if>
		<if test="lastName!=null &amp;&amp; lastName!=&quot;&quot;">
			and last_name like #{lastName}
		</if>
		<if test="email!=null and email.trim()!=&quot;&quot;">
			and email=#{email}
		</if>
		<!-- gender 类型是字符串为什么不出错呢?ognl会进行字符串与数字的转换判断  "0"==0 -->
		<if test="gender==0 or gender==1">
			and gender=#{gender}
		</if>
	</where>
</select>
// 接口
public List<Employee> getEmpsByConditionIf(Employee employee);
// 测试
@Test
public void testDynamicSql() throws IOException{
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try{
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        Employee employee = new Employee(null, "小明", null, null);
		List<Employee> emps = mapper.getEmpsByConditionIf(employee );
		for (Employee emp : emps) {
			System.out.println(emp);
		}
    }finally{
        openSession.close();
    }
}

在这里插入图片描述

3.2 set

演示一个更新语句可能会出现的问题。

<!--public void updateEmp(Employee employee);  -->
<update id="updateEmp">
	update employee
	set
	<if test="lastName!=null">
		last_name=#{lastName},
	</if>
	<if test="email!=null">
		email=#{email},
	</if>
	<if test="gender!=null">
		gender=#{gender}
	</if>
	where id=#{id}
</update>
// 接口
public void updateEmp(Employee employee);
// 测试
@Test
public void testDynamicSql03() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try {
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        Employee employee = new Employee(1, "小小王", null, null);
        mapper.updateEmp(employee);
        openSession.commit();
    } finally {
        openSession.close();
    }
}

在这里插入图片描述
上面的语法报错可以使用set标签和trim标签来解决。

set标签方式

<!--public void updateEmp(Employee employee);  -->
<update id="updateEmp">
	update employee
	<!--set-->
	<set>
		<if test="lastName!=null">
			last_name=#{lastName},
		</if>
		<if test="email!=null">
			email=#{email},
		</if>
		<if test="gender!=null">
			gender=#{gender}
		</if>
	</set>
	where id=#{id}
</update>
// 接口
public void updateEmp(Employee employee);
// 测试
@Test
public void testDynamicSql03() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try {
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        Employee employee = new Employee(1, "小小王", null, null);
        mapper.updateEmp(employee);
        openSession.commit();
    } finally {
        openSession.close();
    }
}

在这里插入图片描述

trim标签方式

<!--public void updateEmp(Employee employee);  -->
<update id="updateEmp">
	update employee
	<trim prefix="set" suffixOverrides=",">
		<if test="lastName!=null">
			last_name=#{lastName},
		</if>
		<if test="email!=null">
			email=#{email},
		</if>
		<if test="gender!=null">
			gender=#{gender}
		</if>
	</trim>
	where id=#{id}  
</update>
// 接口
public void updateEmp(Employee employee);
// 测试
@Test
public void testDynamicSql03() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try {
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        Employee employee = new Employee(1, "小小王王", null, null);
        mapper.updateEmp(employee);
        openSession.commit();
    } finally {
        openSession.close();
    }
}

3.3 trim

<!--public List<Employee> getEmpsByConditionTrim(Employee employee);  -->
<select id="getEmpsByConditionTrim" resultType="com.ginger.mybatis.bean.Employee">
	select * from employee
	<!--
          后面多出的 and 或者 or where 标签不能解决,而使用 trim 就可以解决。
          trim标签体中是整个字符串拼串后的结果。
              prefix 前缀:prefix给拼串后的整个字符串加一个前缀。
              prefixOverrides 前缀覆盖:去掉整个字符串前面多余的字符串。
              suffix 后缀:suffix给拼串后的整个字符串加一个后缀。
              suffixOverrides 后缀覆盖:去掉整个字符串后面多余的字符串。
    -->
	<!-- 自定义字符串的截取规则 -->
	<trim prefix="where" suffixOverrides="and">
		<if test="id!=null">
			id=#{id} and
		</if>
		<if test="lastName!=null &amp;&amp; lastName!=&quot;&quot;">
			last_name like #{lastName} and
		</if>
		<if test="email!=null and email.trim()!=&quot;&quot;">
			email=#{email} and
		</if>
		<!-- gender 类型是字符串为什么不出错呢?ognl会进行字符串与数字的转换判断  "0"==0 -->
		<if test="gender==0 or gender==1">
			gender=#{gender}
		</if>
	</trim>
</select>
// 接口
public List<Employee> getEmpsByConditionTrim(Employee employee);
// 测试
@Test
public void testDynamicSql02() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try {
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        Employee employee = new Employee(null, "小王", null, null);
        List<Employee> emps2 = mapper.getEmpsByConditionTrim(employee);
        for (Employee emp : emps2) {
            System.out.println(emp);
        }
    } finally {
        openSession.close();
    }
}

在这里插入图片描述

4. foreach

  • 动态 SQL 的另外一个常用的必要操作是需要对一个集合进行遍历,通常是在构建 IN 条件语句的时候。
  • 当迭代列表、集合等可迭代对象或者数组时。
    • index是当前迭代的次数,item的值是本次迭代获取的元素。
  • 当使用字典(或者Map.Entry对象的集合)时。
    • index是键,item是值。

4.1 遍历集合

<!--public List<Employee> getEmpsByConditionForeach(List<Integer> ids);  -->
<select id="getEmpsByConditionForeach" resultType="com.ginger.mybatis.bean.Employee">
    select * from employee
    <!--
        collection指定要遍历的集合:
            list类型的参数会特殊处理封装在map中,map的key就叫list。
            item:将当前遍历出的元素赋值给指定的变量。
            separator:每个元素之间的分隔符。
            open:遍历出所有结果拼接一个开始的字符。
            close:遍历出所有结果拼接一个结束的字符。
            index:索引。遍历list的时候是index就是索引,item就是当前值。
                          遍历map的时候index表示的就是map的key,item就是map的值。

            #{变量名}就能取出变量的值也就是当前遍历出的元素。
    -->
    <foreach collection="ids" item="item_id" separator="," open="where id in(" close=")">
    <!--如果不使用@Param注解来指定map的键值,List 参数默认的键值就是list。-->
    <!--<foreach collection="list" item="item_id" separator="," open="where id in(" close=")">-->
        #{item_id}
    </foreach>
</select>
// 接口
public List<Employee> getEmpsByConditionForeach(@Param("ids")List<Integer> ids);
// 或者不使用@Param注解来指定map的键值。
// public List<Employee> getEmpsByConditionForeach(List<Integer> ids);
// 测试
@Test
public void testDynamicSql04() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try {
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        List<Employee> employees = mapper.getEmpsByConditionForeach(Arrays.asList(1, 2, 3, 4, 5));
        employees.forEach(employee -> System.out.println(employee));
    } finally {
        openSession.close();
    }
}

在这里插入图片描述

4.2 mysql下批量插入两种方式

4.2.1 方式1
<!-- 批量保存 -->
<!--public void addEmps(@Param("emps")List<Employee> emps);  -->
<!--MySQL下批量保存:可以foreach遍历   mysql支持values(),(),()语法-->
<insert id="addEmps">
    insert into employee(id,last_name,email,gender,depa_id)
    values
    <foreach collection="emps" item="emp" separator=",">
    <!--如果不使用@Param注解来指定map的键值,List 参数默认的键值就是list。-->
    <!--<foreach collection="list" item="emp" separator=",">-->
        (#{emp.id},#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
    </foreach>
</insert>
// 接口
public void addEmps(@Param("emps")List<Employee> emps);
// 或者不使用@Param注解来指定map的键值。
// public void addEmps(List<Employee> emps);
// 测试
@Test
public void testDynamicSql05() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try {
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        Employee employee1 = new Employee(6, "小姜", "xiaojiang@qq.com", "1", new Department(1));
        Employee employee2 = new Employee(7, "小唐", "xiaotang@qq.com", "1", new Department(1));
        Employee employee3 = new Employee(8, "小张", "xiaozhang@qq.com", "1", new Department(1));
        mapper.addEmps(Arrays.asList(employee1, employee2, employee3));
        openSession.commit();
    } finally {
        openSession.close();
    }
}

在这里插入图片描述

4.2.2 方式2
<!--
    这种方式需要数据库连接属性 allowMultiQueries=true ,这种分号分隔多个 sql 可以用于其他的批量操作(删除,修改)。
-->
<insert id="addEmps">
    <foreach collection="emps" item="emp" separator=";">
    <!--如果不使用@Param注解来指定map的键值,List 参数默认的键值就是list。-->
    <!--<foreach collection="list" item="emp" separator=",">-->
        insert into employee(id,last_name,email,gender,depa_id)
        values(#{emp.id},#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
    </foreach>
</insert>
// 接口
public void addEmps(@Param("emps")List<Employee> emps);
// 或者不使用@Param注解来指定map的键值。
// public void addEmps(List<Employee> emps);
// 测试 
@Test
public void testDynamicSql05() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try {
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        Employee employee1 = new Employee(9, "小赵", "xiaozhao@qq.com", "1", new Department(1));
        Employee employee2 = new Employee(10, "小陶", "xiaotao@qq.com", "1", new Department(1));
        mapper.addEmps(Arrays.asList(employee1, employee2));
        openSession.commit();
    } finally {
        openSession.close();
    }
}

在这里插入图片描述

4.3 oracle下批量插入两种方式

4.3.1 方式1
<!--
	Oracle数据库批量保存:
	 	Oracle不支持values(),(),();
	 	Oracle支持的批量方式
		 	1、多个insert放在begin - end里面
		 		begin
				    insert into employees(employee_id,last_name,email)
				    values(employees_seq.nextval,'test_001','test_001@ginger.com');
				    insert into employees(employee_id,last_name,email)
				    values(employees_seq.nextval,'test_002','test_002@ginger.com');
				end;
-->
<insert id="addEmps" databaseId="oracle">
	<!-- oracle第一种批量方式 -->
	<foreach collection="emps" item="emp" open="begin" close="end;">
		insert into employees(employee_id,last_name,email)
		values(employees_seq.nextval,#{emp.lastName},#{emp.email});
	</foreach> 
</insert>
4.3.2 方式2
<!--
	Oracle数据库批量保存:
		Oracle不支持values(),(),();
		Oracle支持的批量方式
			2、利用中间表:
				insert into employees(employee_id,last_name,email)
			       select employees_seq.nextval,lastName,email from(
			              select 'test_a_01' lastName,'test_a_e01' email from dual
			              union
			              select 'test_a_02' lastName,'test_a_e02' email from dual
			              union
			              select 'test_a_03' lastName,'test_a_e03' email from dual
			       )
-->
<!-- oracle第二种批量方式 -->
<insert id="addEmps" databaseId="oracle">
	insert into employees(employee_id,last_name,email)
	<foreach collection="emps" item="emp" separator="union" 
	open="select employees_seq.nextval,lastName,email from(" close=")">
		select #{emp.lastName} lastName,#{emp.email} email from dual
	</foreach>
</insert>

5. 内置参数 _parameter 和 databaseId

<!-- Mybatis 主配置文件 -->
<!-- 
	4、environments:环境们,mybatis可以配置多种环境 ,default指定使用某种环境。可以达到快速切换环境。
	   environment:配置一个具体的环境信息;必须有两个标签;id代表当前环境的唯一标识。
	   transactionManager:事务管理器;
	      type:事务管理器的类型;JDBC(JdbcTransactionFactory)|MANAGED(ManagedTransactionFactory)
		  自定义事务管理器:实现TransactionFactory接口.type指定为全类名。
		
	   dataSource:数据源;
		  type:数据源类型;UNPOOLED(UnpooledDataSourceFactory)
							|POOLED(PooledDataSourceFactory)
							|JNDI(JndiDataSourceFactory)
		  自定义数据源:实现DataSourceFactory接口,type是全类名。
-->	 
<environments default="dev_mysql">
	<environment id="dev_mysql">
		<transactionManager type="JDBC"></transactionManager>
		<dataSource type="POOLED">
			<property name="driver" value="${jdbc.driver}" />
			<property name="url" value="${jdbc.url}" />
			<property name="username" value="${jdbc.username}" />
			<property name="password" value="${jdbc.password}" />
		</dataSource>
	</environment>
	<environment id="dev_oracle">
		<transactionManager type="JDBC" />
		<dataSource type="POOLED">
			<property name="driver" value="${orcl.driver}" />
			<property name="url" value="${orcl.url}" />
			<property name="username" value="${orcl.username}" />
			<property name="password" value="${orcl.password}" />
		</dataSource>
	</environment>
</environments>

<!-- 
	5、databaseIdProvider:支持多数据库厂商的;
	      type="DB_VENDOR":VendorDatabaseIdProvider。
		 	作用就是得到数据库厂商的标识(驱动getDatabaseProductName()),mybatis就能根据数据库厂商标识来执行不同的sql;
		 	MySQL,Oracle,SQL Server,xxxx。
-->
<databaseIdProvider type="DB_VENDOR">
	<!-- 为不同的数据库厂商起别名 -->
	<property name="MySQL" value="mysql"/>
	<property name="Oracle" value="oracle"/>
	<property name="SQL Server" value="sqlserver"/>
</databaseIdProvider>
<!-- Mybatis 映射文件 -->
<!-- 
	两个内置参数:
		不只是方法传递过来的参数可以被用来判断,取值。
		mybatis默认还有两个内置参数:
			_parameter:代表整个参数
				单个参数:_parameter就是这个参数
				多个参数:参数会被封装为一个map;_parameter就是代表这个map
			
			_databaseId:如果配置了databaseIdProvider标签。
				_databaseId就是代表当前数据库的别名oracle
-->
<!-- public List<Employee> getEmpsTestInnerParameter(Employee employee);  -->
<select id="getEmpsTestInnerParameter" resultType="com.ginger.mybatis.bean.Employee">
		<!-- mysql环境 -->
		<if test="_databaseId=='mysql'">
			select * from employee
			<if test="_parameter!=null"> <!-- _parameter在这里就代表employee这个对象。 -->
				where last_name like #{lastName}
				<!--where last_name like #{_parameter.lastName} 也可以这样取出参数 -->
			</if>
		</if>
		
		<!-- oracle环境 -->
		<if test="_databaseId=='oracle'">
			select * from tbl_employee
			<if test="_parameter!=null"> <!-- _parameter在这里就代表employee这个对象。 -->
				where last_name like #{_parameter.lastName}
			</if>
		</if>
</select>
// 接口
public List<Employee> getEmpsTestInnerParameter(Employee employee);
// 测试 这里我只测试Mysql环境
@Test
public void testDynamicSql06() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try {
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        List<Employee> employees = mapper.getEmpsTestInnerParameter(new Employee(null,"%小%",null,null));
        employees.forEach(emp -> System.out.println(emp));
    } finally {
        openSession.close();
    }
}

在这里插入图片描述

6. bind

bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文。

提个需求上面使用模糊查询 last_name 使用mapper.getEmpsTestInnerParameter(new Employee(null,"%小%",null,null)); 但是有的时候不想再传参的时候使用%号那怎么办呢?

在 #{} 前后面拼接上 % 是否可行?肯定会报错,#{} 表示一个占位符。

<!--public List<Employee> getEmpsTestInnerParameter(Employee employee);  -->
<select id="getEmpsTestInnerParameter" resultType="com.ginger.mybatis.bean.Employee">
    <!-- mysql环境 -->
    <if test="_databaseId=='mysql'">
        select * from employee
		<if test="_parameter!=null"> <!-- _parameter在这里就代表employee这个对象。 -->
		    where last_name like '%#{lastName}%'
		</if>
	</if>
</select>

可以使用${}在前后面拼接上%是可以的,但是这样做不安全。不推荐

<!--  public List<Employee> getEmpsTestInnerParameter(Employee employee);  -->
<select id="getEmpsTestInnerParameter" resultType="com.ginger.mybatis.bean.Employee">
     <!-- mysql环境 -->
     <if test="_databaseId=='mysql'">
         select * from employee
         <if test="_parameter!=null"> <!-- _parameter在这里就代表employee这个对象。 -->
             where last_name like '%${lastName}%'
         </if>
     </if>
</select>
@Test
public void testDynamicSql06() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try {
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        List<Employee> employees = mapper.getEmpsTestInnerParameter(new Employee(null,"小",null,null));
        employees.forEach(emp -> System.out.println(emp));
    } finally {
        openSession.close();
    }
}

测试结果
在这里插入图片描述
如果我就要使用#{},那怎么办呢? 可以使用bind标签。

<!--  public List<Employee> getEmpsTestInnerParameter(Employee employee);  -->
<select id="getEmpsTestInnerParameter" resultType="com.ginger.mybatis.bean.Employee">
    <!-- mysql环境 -->
    <if test="_databaseId=='mysql'">
        <!-- bind:可以将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值 -->
        <bind name="_lastName" value="'%'+lastName+'%'"/>
        <if test="_databaseId=='mysql'">
            select * from employee
            <if test="_parameter!=null">
                where last_name like #{_lastName}
            </if>
        </if>
    </if>
</select>
//接口
public List<Employee> getEmpsTestInnerParameter(Employee employee);

//测试
@Test
public void testDynamicSql06() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try {
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        List<Employee> employees = mapper.getEmpsTestInnerParameter(new Employee(null,"小",null,null));
        employees.forEach(emp -> System.out.println(emp));
    } finally {
        openSession.close();
    }
}

测试结果
在这里插入图片描述

7. sql

<!--
	抽取可重用的sql片段,方便后面引用。
		1、sql抽取:经常将要查询的列名,或者插入用的列名抽取出来方便引用。
		2、include来引用已经抽取的sql。
		3、include还可以自定义一些property,sql标签内部就能使用自定义的属性。
			include-property:取值的正确方式${prop},#{不能使用这种方式否则出错}
-->
<sql id="insertColumn">
	<if test="_databaseId=='mysql'">
		id,last_name,email,gender,depa_id
	</if>
	<if test="_databaseId=='oracle'">
		employee_id,last_name,email
	</if>
</sql>

<!-- 批量保存 -->
<!--public void addEmps(@Param("emps")List<Employee> emps);  -->
<!--MySQL下批量保存:可以foreach遍历   mysql支持values(),(),()语法-->
<insert id="addEmps">
    <!-- insert into employee(id,last_name,email,gender,depa_id) -->
    insert into employee(
        <include refid="insertColumn"></include>
    )
    values
    <foreach collection="emps" item="emp" separator=",">
        <!--如果不使用@Param注解来指定map的键值,List 参数默认的键值就是list。-->
        <!--<foreach collection="list" item="emp" separator=",">-->
        (#{emp.id},#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
    </foreach>
</insert>

<!--
    Oracle数据库批量保存:
        Oracle不支持values(),(),();
        Oracle支持的批量方式
            1、多个insert放在begin - end里面
                begin
                    insert into employees(employee_id,last_name,email)
                    values(employees_seq.nextval,'test_001','test_001@ginger.com');
                    insert into employees(employee_id,last_name,email)
                    values(employees_seq.nextval,'test_002','test_002@ginger.com');
                end;
-->
<insert id="addEmps" databaseId="oracle">
    <!-- oracle第一种批量方式 -->
    <foreach collection="emps" item="emp" open="begin" close="end;">
        <!--insert into employees(employee_id,last_name,email)-->
        insert into employees(
            <include refid="insertColumn"></include>
        )
        values(employees_seq.nextval,#{emp.lastName},#{emp.email});
    </foreach>
</insert>
//接口
public void addEmps(@Param("emps")List<Employee> emps);
//或者不使用@Param注解来指定map的键值。
//public void addEmps(List<Employee> emps);


//测试 这里我只测试Mysql环境
@Test
public void testDynamicSql05() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try {
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        Employee employee1 = new Employee(11, "小钱", "xiaoqian@qq.com", "1", new Department(1));
        Employee employee2 = new Employee(12, "小林", "xiaolin@qq.com", "1", new Department(1));
        mapper.addEmps(Arrays.asList(employee1, employee2));
        openSession.commit();
    } finally {
        openSession.close();
    }
}

在这里插入图片描述

在 include 标签中添加自定义属性在 sql 标签中获取。

<sql id="insertColumn">
    <if test="_databaseId=='mysql'">
        id,last_name,email,gender,depa_id,${testColumn}
    </if>
    <if test="_databaseId=='oracle'">
        employee_id,last_name,email
    </if>
</sql>

<!-- 批量保存 -->
<!--public void addEmps(@Param("emps")List<Employee> emps);  -->
<!--MySQL下批量保存:可以foreach遍历   mysql支持values(),(),()语法-->
<insert id="addEmps">
    <!-- insert into employee(id,last_name,email,gender,depa_id) -->
    insert into employee(
        <include refid="insertColumn">
            <property name="testColumn" value="test"></property>
        </include>
    )
    values
    <foreach collection="emps" item="emp" separator=",">
        <!--如果不使用@Param注解来指定map的键值,List 参数默认的键值就是list。-->
        <!--<foreach collection="list" item="emp" separator=",">-->
        (#{emp.id},#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
    </foreach>
</insert>
//接口
public void addEmps(@Param("emps")List<Employee> emps);
//或者不使用@Param注解来指定map的键值。
//public void addEmps(List<Employee> emps);


//测试 肯定会出错,因为没有这个列,我就是想演示一下在 include 自定义属性在 sql 标签中获取。
@Test 
public void testDynamicSql07() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try {
        EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
        Employee employee1 = new Employee(13, "小郭", "xiaoguo@qq.com", "0", new Department(2));
        mapper.addEmps(Arrays.asList(employee1));
        openSession.commit();
    } finally {
        openSession.close();
    }
}

在这里插入图片描述

mybatis教程4(动态SQL) 动态SQL语句 MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。 虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的... 阅读详情

相关推荐

IQA图像质量评价 数据集介绍(LIVE、TID2013、CSIQ、LIVEC、KonIQ-10K)

LIVE、TID2013、CSIQ、LIVEC、KonIQ-10K 数据集介绍

qq_37925923的博客 1万+

MyBatis4(动态SQL注解 脚本动态sql 方法中构建sql SQL 语句构造器 分页 延迟加载和立即加载(表联查) 了解一级缓存和二级缓存的功能(基本上不用,面试))

XML配置方式的动态SQL,是 用的方式把它照搬过来,用注解来实现。适用于xml 配置转换到注解配置@SelectProvider @InsertProvider @UpdateProvider @DeleteProvider 这些方法的使用实现动态 SQL 的内容。

qq_52897007的博客 1293

缺陷检测-金属表面缺陷检测

1介绍 缺陷检测是工业视觉技术中最重要的组成部分。业务广泛,场景丰富,技术难点高、工作量大。针对不同的场景,选择不同的相机和

huneng1991的专栏 5263

【MyBatis-4】MyBatis之动态SQL

MyBatis之动态SQL1 if2 choose, when, otherwise3 trim, where, set3 foreach4 bind5 多数据库支持6 动态 SQL 中的可插拔脚本语言 本文内容来自Mybatis文档,在此整理分享给大家。 MyBatis 的强大特性之一便是它的动态 SQL。 1 if 动态 SQL 通常要做的事情是根据条件包含 where 子句的一部分。比如: ...

云深不知处 1万+

理想汽车智驾方案介绍 4 World model + 强化学习重建自动驾驶交互环境

本帖将以 DrivingSphere 为例来解析这个过程。

地平线开发者 1928

★教程3:Simulink学习教程入门60例目录

1.订阅本教程用户可以免费获得本博任意1个(包括所有免费专栏和付费专栏)博文对应代码;2.本Simulink课程的所有案例(部分理论知识点除外)均由博主编写而成,供有兴趣的朋友们自己订阅学习使用。未经本人允许,禁止任何形式的商业用途;3.本课程除了介绍常见的Simulink模块介绍之外,我们更侧重于各种实例的完整设计介绍。从通信,控制器,图像处理,语音处理,电力系统等诸多常用领域介绍了相关案例,如果对于某个较为复杂的案例,初学者无法正确复现,也可以私信博主获得完整Simulink模型文件。

FPGA/MATLAB学习教程/源码/项目合作开发 1万+

Mybatis4 Mybatis动态sql的实现

###1.什么是动态SQL SQL语句不固定, 会根据前台用户的操作而进行变化的SQL语句, 可以被称之为动态SQL. 在MyBatis中, 提供了一组标签, 用于方便的实现动态SQL, 不需要通过java代码拼接字符串了. ###2.动态sql中的标签 ######1. 用于条件判断, test属性表示判断结果, 要求是一个boolean. ######2. 用于维护where子句, 通常配合一...

风泊月 491

LSTM 深度解析从原理推演到现代序列建模的演进

LSTM(Long Short-Term Memory,长短期记忆网络)是一种特殊的递归神经网络(RNN),它通过引入记忆单元(Cell State)来解决普通RNN在长序列数据处理中的梯度消失问题。LSTM可以在长时间的序列中捕捉依赖关系,是一种非常适合处理时间序列、自然语言处理、语音识别等任务的深度学习模型。在LSTM中,记忆单元(Cell State)是一个贯穿整个序列的数据通道,用于存储和传递关键信息。记忆单元在LSTM的时间步之间保持信息的持久性,可以看作是一个长期记忆的“容器”。

hello.reader 3万+

【Mybatis】4—动态SQL

Mybatis框架的动态SQL技术是一种 根据特定条件动态拼装SQL语句 的功能,它存在的意义是为了解决拼接SQL语句字符串时的痛点问题。MyBatis的一个强大的特性之一通常是它的动态SQL能力。

一棵灬大树的博客 1213

Python画柱状图(双柱状图,三柱状图)且显示对应数值

使用python实现双柱状图和三柱状图,并且在柱状图形的顶部显示对应数值;

yue200403的博客 1万+

基于RK3588调试WiFi模块AIC8800

本文介绍了在RK3588平台上移植AIC8800 WiFi模块驱动的过程。开发环境基于Linux 6.1内核和Buildroot文件系统。驱动移植步骤包括:将驱动包放入SDK指定目录、修改Makefile、编译内核、放置固件文件、手动加载驱动模块等。文章还分析了两种常见异常情况:无法识别模块(检查USB信号线路和供电)和偶发断连(检查硬件连接和调整PHY寄存器)。成功加载后可通过ifconfig看到wlan0节点。

qq_45147279的博客 681

MyBatis4:动态SQL

转载:MyBatis4:动态SQL 什么是动态SQL MyBatis的一个强大特性之一通常是它的动态SQL能力。如果你有使用JDBC或其他相似框架的经验,你就明白条件串联SQL字符串在一起是多么地痛苦,确保不能忘了空格或者在列表的最后的省略逗号,动态SQL可以彻底处理这种痛苦。 通常使用动态SQL不可能是独立的一部分,MyBatis当然使用一种强大的动态SQL语言来改进这种情形,这种语言可以...

weixin_30359021的博客 95

【YOLO26实战全攻略】10——YOLO26+SAM3实战:从检测到像素级分割的全流程指南(含PCB缺陷检测案例)

本文聚焦YOLO26与SAM3的融合应用,系统讲解“检测+分割”的三种核心模式:YOLO26原生分割(轻量高效)、YOLO26检测+SAM3精细分割(精度极致)、SAM3自动标注+YOLO26蒸馏(低成本冷启动)。从环境搭建、数据集准备、模型训练、性能优化到边缘部署,提供 step-by-step 实操教程,配套完整可运行代码与执行结果。结合虚拟PCB缺陷检测案例,展示像素级缺陷识别与几何参数测量的工业级应用流程。本文兼顾新手入门与进阶提升,注重实用价值,读者可直接参考搭建自己的分割系统。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 648

4.mybatis动态sql

1.if <select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <if test="title != null"> AND title like #{title} </if> <if te...

qq_24664619的博客 144

InTheHand.Net.Personal+BlueTooth4,蓝牙开发

项目中有蓝牙开发的必备dll,现在网上相关的文档博客不少,有的说的多有的说少,但是却很少有这两个dll,分享一下。

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Mybatis学习4之动态SQL

(一)简介 Mybatis提供了SQL语句动态的组装能力,它所包含的几个元素也非常简单,SQL语句的组装可以在XML映射文件中配置,也可以使用注解,但是使用注解配置功能会受到限制。 Mybatis的动态SQL包括如下的元素: if:判断语句,单条件分支判断; choose(when,otherwise):相当于Java中的case,when语句,多条件分支判断; trim(where,set):辅...

kenewstar的博客 1031

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

(4)Mybatis的动态SQL

文章目录前言1.if标签1.1.应用场景1.2.实现修改Product.xml在测试类Test中添加第六个测试函数输出为什么不用resultMap呢1.3.传入参数是map集合的动态sql语句2.where标签2.1.应用场景2.2.实现修改Product.xml在测试类Test中添加第七个测试函数输出3.set标签3.1.应用场景3.2.实现修改Product.xml在测试类Test中添加第八个...

QAQ123666的博客 240

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

mybatis4:动态sql

学习

qq_44724899的博客 805

mybatis(4)Mybatis解析动态sql原理分析

出自:https://www.cnblogs.com/fangjian0423/p/mybaits-dynamic-sql-analysis.html Mybatis解析动态sql原理分析 前言 废话不多说,直接进入文章。 我们在使用mybatis的时候,会在xml中编写sql语句。 比如这段动态sql代码: <update id="update" parameterType="org....

cowbin2012的专栏 1万+

Mybatis-4 动态SQL

动态SQL:if语句 根据 username 和 sex 来查询数据。如果username为空,那么将只根据sex来查询;反之只根据username来查询 首先不使用 动态SQL 来书写 <select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User"> <!-- 这里和普通的sql 查询语句差不多,对于只有一个参数,后面的 #{id}表示占位符,里面不一

weixin_43887870的博客 229

MyBatis 4. 动态 SQL

动态 SQL MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦。拼接的时候要确保不能忘了必要的空格,还要注意省掉列名列表最后的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。 通常使用动态 SQL 不可能是独立的一部分,MyBatis 当然使用一种强大的动态 SQL 语言来...

我心中全是学习 226

mybatis4动态SQL

动态SQL等 动态SQL是Mybatis的一个强大特性,在使用JDBC操作数据时,如果查询条件特别多,将条件串联成SQL字符串是一件痛苦的事情,通常的解决方法是写很多的if-else条件语句对字符串进行拼接.并确保不能忘了空格或在字段的最后省略逗号.Mybatis使用一种强大的的动态Sql语言来改善这种情形.动态SQL基于OGNL的表达式,可使我们方便的在SQL语句中实现某些逻辑,用于实现动态SQL的元素如下: 实现动态SQL的元素(9个标签)  if:利用if实现简单的条件选择  choose(whe

GodfatherTye的博客 232

第4章 MyBatis 动态SQL

第4章 MyBatis 动态SQL

与海 605

【MyBatis】(4)动态SQL

前言 该文章记录了MaBatis动态SQL常用标签。 一、动态SQL 介绍 动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。 使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映...

长生的梦呓 375

MyBatis:NO4 —— 动态SQL

1.概述 动态SQL:通过不同的查询条件,生成不同的SQL语句。防止业务需要使用复杂的SQL语句进行拼接而造成的错误 官网描述: MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你 就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意 去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。 虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映

note_hsy的博客 272
上一篇: Mybatis3_映射文件
下一篇: Mybatis5_缓存机制
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值