笔记要点-----内置参数_parameter&_databaseId 用处: 迅速切换数据库,执行一条多分支的sql语句即可;
1.定义接口
public interface EmployeeMapper_DynamicSQL { public List<Employee> getEmpsTestInnerParameter(Employee employee);//测试内部参数 }
2.定义XML映射文件
<!--两个内置参数;不只是方法传递过来的参数可以用来判断,取值 mubatis默认还有两个内置参数: _parameter : 代表整个参数; 单个参数: _parameter就是这个参数 多个参数: 会被封装成一个map,map就是_parameter _databaseId : 如果配置了databaseIdProvider标签; _databaseId就是代表了当前数据库的别名mysql ! --> <!--public List<Employee> getEmpsTestInnerParameter(Employee employee);//测试内部参数--> <select id="getEmpsTestInnerParameter" resultType="com.bean.Employee"> <if test="_databaseId=='mysql'"> select * from tbl_employee <if test="_parameter!=null"> where last_name = #{_parameter.lastName} </if> </if> <if test="_databaseId=='oracle'"> select * from tbl_employee </if>
3.编写测试代码
public class test_tp48 { public SqlSessionFactory getSqlSessionFactory() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(inputStream); } @Test public void test11() throws Exception { SqlSession openSession = getSqlSessionFactory().openSession(); try { System.out.println("++++++++++---- tp48.测试动态sql_内置参数_parameter&_databaseId"); EmployeeMapper_DynamicSQL mapper = openSession.getMapper(EmployeeMapper_DynamicSQL.class); List<Employee> list = mapper.getEmpsTestInnerParameter(null); for(Employee e:list) System.out.println(e); openSession.commit(); } finally { openSession.close(); } } }
测试结果
++++++++++---- tp48.测试动态sql_内置参数_parameter&_databaseId DEBUG 12-05 17:45:17,805 ==> Preparing: select * from tbl_employee (BaseJdbcLogger.java:145) DEBUG 12-05 17:45:17,828 ==> Parameters: (BaseJdbcLogger.java:145) DEBUG 12-05 17:45:17,845 <== Total: 8 (BaseJdbcLogger.java:145) Employee{id=1, lastName='Jerry2333', email='233@...', gender='1', dept=null} Employee{id=4, lastName='葫芦娃', email='葫芦娃@163.com', gender='0', dept=null} Employee{id=5, lastName='葫芦娃e', email='qwq@qq.com', gender='1', dept=null} Employee{id=6, lastName='null', email='xxx@qq.com', gender='1', dept=null} Employee{id=7, lastName='tom', email='tom@163.com', gender='0', dept=null} Employee{id=8, lastName='frak', email='frak@163.com', gender='1', dept=null} Employee{id=9, lastName='smith', email='smith@qq.com', gender='1', dept=null} Employee{id=10, lastName='aliex', email='aliex@qq.com', gender='0', dept=null}