zoukankan      html  css  js  c++  java
  • MyBaits动态sql语句

    1 在接口中书写方法

    public interface EmployeeMapperDynamicSQL {

    public List<Employee> getEmpsTestInnerParameter(Employee employee);

    }

    2在映射中进行配置

    <!-- 查询员工,要求,携带了哪个字段查询条件就带上这个字段的值 -->
    <!-- public List<Employee> getEmpsByConditionIf(Employee employee); -->
    <select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">
    select * from tbl_employee
    <!-- where -->
    <where>
    <!-- test:判断表达式(OGNL)
    OGNL参照PPT或者官方文档。
    c:if test
    从参数中取值进行判断

    遇见特殊符号应该去写转义字符:
    &&:
    -->
    <if test="id!=null">
    id=#{id}
    </if><!-- &amp;为& &quot;为“ -->
    <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>
    <!-- ognl会进行字符串与数字的转换判断 "0"==0 -->
    <if test="gender==0 or gender==1">
    and gender=#{gender}
    </if>
    </where>
    </select>


    3进行测试

    public SqlSessionFactory getSqlSessionFactory() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    return new SqlSessionFactoryBuilder().build(inputStream);
    }

    @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 ?
    //测试ifwhere
    Employee employee = new Employee(null, "jerry2", null, null);
    List<Employee> emps = mapper.getEmpsByConditionIf(employee );
    for (Employee emp : emps) {
    System.out.println(emp);
    }
    }finally{
    openSession.close();
    }
    }

  • 相关阅读:
    final-第十章
    路由器基本配置-命令行配置模式
    路由器基本配置-对话配置模式
    配置静态路由
    默认路由
    像素值的读写
    矩阵的基本元素表达
    创建Mat对象
    Mat类
    数学基础-3D空间的位置表示
  • 原文地址:https://www.cnblogs.com/zhangzhiqin/p/8558684.html
Copyright © 2011-2022 走看看