不只是方法传递过来的参数可以被用来判断,取值,mybatis
默认还有两个内置参数:
_parameter
:代表整个参数
- 单个参数:
_parameter
就是这个参数 - 参数会被封装为一个
map
;_parameter
就是代表这个map
- 单个参数:
_databaseId
:如果配置了databaseIdProvider
标签。
_databaseId
就是代表当前数据库的别名
我们用实例讲解一下:
在EmployeeMapperDynamicSQL.java
中写一个方法:
public List<Employee> getEmpsTestInnerParameter(Employee employee);
然后到EmployeeMapperDynamicSQL.xml
中实现方法:
还可以用test="_parameter!=null"
这样的方式在查询时带上条件
<select id="getEmpsTestInnerParameter" resultType="com.atguigu.mybatis.bean.Employee">
<!-- bind:可以将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值 -->
<if test="_databaseId=='mysql'">
select * from tbl_employee
<if test="_parameter!=null">
where last_name = #{lastName}
</if>
</if>
<if test="_databaseId=='oracle'">
select * from employees
<if test="_parameter!=null">
where last_name = #{_parameter.lastName}
</if>
</if>
</select>
测试:
@Test
public void testInnerParam() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
Employee employee2 = new Employee();
List<Employee> list = mapper.getEmpsTestInnerParameter(employee2);
for (Employee employee : list) {
System.out.println(employee);
}
}finally{
openSession.close();
}
}
然后就可以在全局配置文件中切换数据库查询了:
bind:绑定
我们来改一下方法实现:
改成模糊查询用like
<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 #{_lastName}
</if>
</if>
</select>
然后测试方法传入一个查名字中带有e
字母的employee
对象:
@Test
public void testInnerParam() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
Employee employee2 = new Employee();
// 如果不用<bind>标签要这样写 employee2.setLastName("%e%");
employee2.setLastName("e");
List<Employee> list = mapper.getEmpsTestInnerParameter(employee2);
for (Employee employee : list) {
System.out.println(employee);
}
}finally{
openSession.close();
}
}