前言:
本篇博客仅仅作为笔录,避免每次网络搜索
前期准备:
- sql :
CREATE TABLEtb_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’);
2.实体类 StudentInfo:
public class StudentInfo {
private Integer id; private String name; private Integer age; // 省略 get、set 方法
- }
示例:
- 通过 两种不同数据类型的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>