mybatis学习05 动态SQL

动态SQL

       数据库表

      

实现动态SQL

实体类略

  1. SQL语句映射

 

   <!-- 动态SQL -->

  

   <select id="getStudent"  parameterType="Map" resultType ="com.master.Students">

      select*from students

      <where>

         <if test="s_sex!=null">

            s_sex=#{s_sex}

         </if>

        

         <if test="c_id!=null">

            and c_id=#{c_id}

         </if>

      </where>

   </select>

Select里面的where标签提供了if 能够自动判断test里面的参数是否存在,如果存在则动态添加if里面的SQL语句

业务类

public List<Students> getStudents(Map<String, String> map) throws IOException

   {

      SqlSession ss=MybatisUit.getSession();

      List<Students> list= ss.selectList("com.master.Students.mapper.getStudent", map);

      return list;

   }

测试

  1. 在不设置参数的情况下

public static void main(String[] args) throws IOException {

    StudentsDao sd=new StudentsDao();

    List<Students> list=sd.getStudents(null);

    for (Students stu:list)

    {

       System.out.println(stu);

    }

}

结果

不设置参数执行的SQL语句为select*from students

  1. 设置一个参数的情况:查找c_id=001的学生

public static void main(String[] args) throws IOException {

    StudentsDao sd=new StudentsDao();

    Map<String, String> map=new HashMap<String, String>();

    map.put("c_id", "001");

    List<Students> list=sd.getStudents(map);

    for (Students stu:list)

    {

       System.out.println(stu);

    }

}

              结果:

 

C)设置两个参数 查找c_id=001且性别为男性的学生

public static void main(String[] args) throws IOException {

      StudentsDao sd=new StudentsDao();

      Map<String, String> map=new HashMap<String, String>();

      map.put("c_id", "001");

      map.put("s_sex", "");

      List<Students> list=sd.getStudents(map);

      for (Students stu:list)

      {

         System.out.println(stu);

      }

   }

结果:

 

 

动态SQL可以用于搜索界面的条件筛选等功能

猜你喜欢

转载自blog.csdn.net/u012777599/article/details/88677908
今日推荐