手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

mybatis动态sql使用bind绑定

时间:2024-10-12 20:27:26

1、bind绑定可以将ognl表达式的值绑定到一个变量中,方便后来引用这个变量的值。<bind name="_empName" value="'%' + empName +'%'"/>

mybatis动态sql使用bind绑定

2、假如我们想要模糊查询员工姓名:<select id="getEmpsByConditionChoose" resultMap="MyEmpByStep" databaseId="mysql"> select * from tbl_emp <where> <if test="empId!=null"> emp_id = #{empId} </if> <if test="empName!=null"> and emp_name like #{_empName} </if> </where> </select>

mybatis动态sql使用bind绑定

3、编写单元测试代码:@Test public void test1() throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class); Employee employee = new Employee(); employee.setEmpId(1); employee.setEmpName("%曹%"); List<Employee> employees = employeeMapper.getEmpsByConditionChoose(employee); System.out.println(employees); }finally { sqlSession.close(); } }

mybatis动态sql使用bind绑定

4、假如我们想要这个百分号不要写在代码,而是想写在sql语句中,可以使用bind标签进行绑定<select id="getEmpsByConditionChoose" resultMap="MyEmpByStep" databaseId="mysql"> select * from tbl_emp <bind name="_empName" value="'%' + empName +'%'"/> <where> <if test="empId!=null"> emp_id = #{empId} </if> <if test="empName!=null"> and emp_name like #{_empName} </if> </where> </select>

mybatis动态sql使用bind绑定

5、运行单元测试方法,查看后台打印的sql语句。

mybatis动态sql使用bind绑定
mybatis动态sql使用bind绑定

6、模糊溽朽孑臾查询我们推荐使用在代码中使用%传值。public void test1() throws Excepti泠贾高框on { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class); Employee employee = new Employee(); employee.setEmpId(1); employee.setEmpName("%曹%"); List<Employee> employees = employeeMapper.getEmpsByConditionChoose(employee); System.out.println(employees); }finally { sqlSession.close(); } }

mybatis动态sql使用bind绑定
© 手抄报圈