• 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();
    }
    }

  • 相关阅读:
    [LeetCode] Range Sum Query
    [LeetCode] Longest Increasing Subsequence
    [LeetCode] Bulls and Cows
    [LeetCode] Serialize and Deserialize Binary Tree
    [LeetCode] Find Median from Data Stream
    [LeetCode] Convert Sorted List to Binary Search Tree
    [LeetCode] Nim Game
    [LeetCode] Word Pattern
    安装配置说明与注意
    java.lang.OutOfMemoryError: PermGen space及其解决方法
  • 原文地址:https://www.cnblogs.com/zhangzhiqin/p/8558684.html
Copyright © 2020-2023  润新知