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

  • 相关阅读:
    ORA-02290: 违反检查约束条件
    上传图片
    dart视频教程
    'OFFSET' 附近有语法错误。 在 FETCH 语句中选项 NEXT 的用法无效。
    .net js有数据 但是跳转不到操作页
    LAYUI layedit 富文本框内容的取值
    LAYUI select 下拉框得高度
    防止页面刷新
    Hadoop常用命令
    spark常用命令
  • 原文地址:https://www.cnblogs.com/zhangzhiqin/p/8558684.html
Copyright © 2011-2022 走看看