Mybatis處理List參數

前言:

本篇博客僅僅作爲筆錄,避免每次網絡搜索

前期準備:

  1. sql :
CREATE TABLE `tb_student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_bin NOT NULL,
  `age` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8 COLLATE=utf8_bin ROW_FORMAT=DYNAMIC;

INSERT INTO `work`.`tb_student` (`id`, `name`, `age`) VALUES ('25', ' Ben ', '23');
INSERT INTO `work`.`tb_student` (`id`, `name`, `age`) VALUES ('26', 'Jack', '24');
INSERT INTO `work`.`tb_student` (`id`, `name`, `age`) VALUES ('27', 'Tom', '24');
INSERT INTO `work`.`tb_student` (`id`, `name`, `age`) VALUES ('28', 'Jerry', '19');
INSERT INTO `work`.`tb_student` (`id`, `name`, `age`) VALUES ('29', 'Lilian', '18');
  1. 實體類 StudentInfo:
public class StudentInfo {

    private Integer id;

    private String name;

    private Integer age;
    
    // 省略 get、set 方法
}

示例:

  1. 通過 兩種不同數據類型的List 不同查詢:

StudentDao :

/**
     * 通過年齡和名稱查詢結果
     * @param ages
     * @param name
     * @return
     */
    List<StudentInfo> getListByAgesAndName(@Param("ages") List<Integer> ages, @Param("name") String name);
    
  /**
     * 通過年齡【實體中獲取】和名稱查詢結果
     * @param studentInfos
     * @param name
     * @return
     */
    List<StudentInfo> getListByStudentInfoAndName(@Param("studentInfos") List<StudentInfo> studentInfos, @Param("name") String name);

StudentMapper.xml

<!-- 通過年齡和名稱查詢結果 -->
    <select id="getListByAgesAndName"  resultType="com.morning.all.entity.StudentInfo">
        select * from  tb_student
        where name like CONCAT('%',#{name},'%')
        and age in
        <foreach collection="ages" item="age" index="index" open="(" close=")" separator=",">
            #{age}
        </foreach>
    </select>

    <!-- 通過年齡【實體中獲取】和名稱查詢結果 -->
    <select id="getListByStudentInfoAndName"  resultType="com.morning.all.entity.StudentInfo">
        select * from  tb_student
        where name like CONCAT('%',#{name},'%')
        and age in
        <foreach collection="studentInfos" item="studentInfo" index="index" open="(" close=")" separator=",">
            #{studentInfo.age}
        </foreach>
    </select>

以上就是關於Mybatis List傳參以及使用!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章