MyBatis(五)動態SQL 之 批量操作(查詢)


一、批量操作——查詢

  在實際工作,我們需要根據情況進行批量查詢,批量查詢,可以全部查詢出來,也可以根據其他查詢查詢出來。

  1、查詢全部的數據

    (1)在接口中聲明方法

//查詢所有對象,返回 list 集合
public List<Employee> getAllEmps();

 

    (2)在對應的 xml 中配置

    <!-- public List<Employee> getAllEmps(); resultType:如果返回的是一個集合,要寫集合中元素的類型 指定集合中存放的類型,有多個數據,會自動轉換為要返回的類型 -->
    <select id="getAllEmps" resultType="com.njf.mybatis.bean.Employee"> select id, last_name lastName, email, gender from tbl_employee </select>

 

  2、根據指定條件批量查詢

    (1)在接口中聲明方法

//根據指定的id來查詢
public List<Employee> getEmpsByIds(@Param("ids")List<Integer> ids);

 

    (2)在對應的 xml 中配置

    <!-- //根據指定的id來查詢 public List<Employee> getEmpsByIds(@Param("ids")List<Integer> ids); -->
    <!-- 方式一:select * from tbl_employee where id in (1,2,3); -->
    <select id="getEmpsByIds" resultType="Employee" databaseId="oracle"> select * from tbl_employee <foreach collection="ids" item="item" open="where id in(" close=")" separator=","> #{item} </foreach>
    </select>

    <!-- 方式二:select * from tbl_employee where id = 1 or id = 2 or id = 3 -->
    <select id="getEmpsByIds" resultType="Employee"> select * from tbl_employee <foreach collection="ids" item="item" open="where" separator="or"> id = #{item} </foreach>
    </select>

 

  3、根據多條件查詢

    (1)在接口中聲明方法

//根據多條件查詢
public List<Employee> getEmpsByCondition(Employee employee);

 

    (2)在對應的 xml 中配置

   <!-- public List<Employee> getEmpsByCondition(Employee employee); -->
    <select id="getEmpsByCondition" resultType="Employee"> select * from tbl_employee <where>
            <if test="id!=null"> id=#{id} </if>
            <if test="lastName!=null and lastName!=''"> and last_name like #{lastName} </if>
            <if test="email!=null and email.trim()!=&quot;&quot;"> and email = #{email} </if>
            <if test="gender!=null and gender==0 or gender==1"> and gender = #{gender} </if>
        </where>
    </select>

 

  測試:

 @Test public void testBatchSelect() throws IOException { //1、獲取 sqlSessionFactory
          SqlSessionFactory sqlSessionFactory = getsqlSessionFactory(); //2、獲取 sqlSession 實例,能直接執行已經映射的 SQL 語句
          SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployeeMapperBatch mapper = sqlSession.getMapper(EmployeeMapperBatch.class); List<Employee> emps = new ArrayList<>(); //查詢所有的員工信息
               emps = mapper.getAllEmps(); //根據指定的id來查詢
               emps = mapper.getEmpsByIds(Arrays.asList(1, 3)); //多條件查詢
               emps = mapper.getEmpsByCondition(new Employee(null, "%o%", null, null)); emps.forEach(System.out::println); } finally { sqlSession.close(); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM