Mybatis同時傳遞實體和分頁數據


在使用mybatis查詢數據庫時,如果需要分頁可以在dao接口方法中傳遞兩個數據,一個是頁數pageNum,一個是一面顯示幾頁pageSize,在Mybatis編譯sql語句時,會將這兩個分頁數據插入到sql語句中,在每個參數前要加上@Param注解,注解中的內容是有規定的,頁數就是pageNum,顯示幾頁是pageSize:

public interface CityDao{
    List<City> listCity(@Param("pageNum") Integer pageNum, @Param("pageSize") Integer pageSize);
}

cityMapper.xml:

<select id="listCity" resultMap="cityMap" parameterType="edu.nf.city.entity.City">
    select city_id, country, province, city_name from city_info
</select>

但是,當還需要傳遞一些條件時,如需要根據City對象中的省份或者城市字段模糊查詢,並實現分頁:

dao:

public interface CityDao{
    List<City> listCity(City city, @Param("pageNum") Integer pageNum, @Param("pageSize") Integer pageSize);  
}

cityMapper.xml(這里使用動態sql查詢):

<!-- 根據province和city_name兩個字段模糊查詢出城市信息並實現分頁,如果city對象為null,則表示查詢所有
 同時,因為在前面還傳了pageNum和pageSize兩個分頁數據,所以在sql中對city對象的取值前面需要加上city對象,
如下: -->
<select id="listCity" resultMap="cityMap" parameterType="edu.nf.city.entity.City">
    select city_id, country, province, city_name from city_info
    <where>
        <if test="city != null">
            <if test="city.province != null and city.province != ''">
                province = #{city.province}
            </if>
            <if test="city.cityName != null and city.cityName != ''">
                and city_name = #{city.cityName}
            </if>
        </if>
    </where>
</select>

 


免責聲明!

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



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