In this step, you will learn how to batch query the course information with the course numbers "1,2,3" using dynamic SQL.
-
Open the CourseMapper.java
file located in the /org/lanqiao/mapper/
directory.
-
Implement the selectCoursesByIds
method in the CourseMapper
interface. This method should accept a Map<String, Object>
parameter to hold the input parameters.
List<Map<String, Object>> selectCoursesByIds(Map<String, Object> params);
-
Open the CourseMapper.xml
file located in the /org/lanqiao/mapper/
directory.
-
Implement the selectCoursesByIds
SQL statement in the CourseMapper
namespace. Use the <foreach>
tag to iterate over the ids
list and build the IN clause.
<select id="selectCoursesByIds" resultMap="courseResultMap" parameterType="java.util.Map">
SELECT * FROM course WHERE cNo IN
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>
-
Open the MyBatisTest.java
file located in the /org/lanqiao/test/
directory.
-
Implement the testSelectCoursesByIds
test method to test the selectCoursesByIds
functionality.
@Test
public void testSelectCoursesByIds() {
CourseMapper mapper = session.getMapper(CourseMapper.class);
List<Integer> ids = Arrays.asList(1, 2, 3);
Map<String, Object> params = new HashMap<>();
params.put("ids", ids);
List<Map<String, Object>> coursesByIds = mapper.selectCoursesByIds(params);
System.out.println(coursesByIds);
}
Run
To make sure that the code works, take care to introduce relevant classes into the code.
CourseMapper.java
:
import org.lanqiao.pojo.Course;
import java.util.List;
import java.util.Map;
MyBatisTest.java
:
import java.util.Arrays;
import java.util.HashMap;
Finally you can compile and run the code in the terminal and check the test files with Maven, using the following commands:
cd MyBatisCourseDemo03
mvn test
You can refer to 👀 Preview
for a running rendering.