MyBatis_MyBatis之动态SQL之内置参数

1.引入

   在映射文件中,我们可以通过传递参数给我们自己写的sql语句进行参数的传递,同时MyBatis自己也提供了俩个内置的参数。

也就是说我们使用ONGL判断传递的参数,内置的参数也可以进行判断和取值操作。

2.MyBatis俩个内置参数

(1)._parameter:代表整个参数

        单个参数:_parameter就是这个参数。
        多个参数:参数会被封装为一个map;_parameter就是代表这个map。

(2)._databaseId:如果配置了databaseIdProvider标签。

          _databaseId就是代表当前数据库的别名MySQL

3.MyBatis俩个内置参数基本使用示例

(1).编写基本的查询方法

public List<Employee> getEmpsTestInnerParameter(Employee employee);

(2).编写配置文件

<select id="getEmpsTestInnerParameter" resultType="com.atguigu.mybatis.bean.Employee">  		
	  		<if test="_databaseId=='mysql'">
	  			select * from tbl_employee
	  			<if test="_parameter!=null">
	  				where last_name like #{lastName}
	  			</if>
	  		</if>
	  		<if test="_databaseId=='oracle'">
	  			select * from employees
	  			<if test="_parameter!=null">
	  				where last_name like #{lastName}
	  			</if>
	  	    </if>
</select>

(3).测试效果

EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
Employee employee2 = new Employee();
employee2.setLastName("%e%");
List<Employee> list = mapper.getEmpsTestInnerParameter(employee2);
for (Employee employee : list) {
	System.out.println(employee);
}

4.添加bind绑定

(1).bind绑定

          可以将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值

(2).通过bind绑定改进内置参数的判断

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

(3).效果测试

EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
Employee employee2 = new Employee();
employee2.setLastName("e");
List<Employee> list = mapper.getEmpsTestInnerParameter(employee2);
for (Employee employee : list) {
	System.out.println(employee);
}

总结:

我们发现,使用bind标签以后,可以在映射文件中使用ONGL表达式规则对传入的参数进行一个新的操作,然后方便在其他的地方引用。

猜你喜欢

转载自blog.csdn.net/u013185175/article/details/107918493
今日推荐