select * from student where id in{1001,1002,1003}
集合实际上就是遍历in后面的id值
在没有标签的时候要想执行 in后面的Arraylist集合需要
public void testfor() {
ArrayList<Integer> list = new ArrayList<>();
list.add(1001);
list.add(1002);
list.add(1003);
String sql = "select * from student where id in";
StringBuilder builder = new StringBuilder("");
int init = 0;
int len = list.size();
//添加开始的(
builder.append("(");
for (Integer i : list) {
builder.append(i).append(",");
}
builder.deleteCharAt(builder.length() - 1);
builder.append(")");
System.out.println("sql=="+sql+builder);
}
dao接口层的代码
//用法 1 传 数组集合
List<Student> selectForeachOne(List<Integer> idlist);
//用法2传对象
List<Student> selectForeachTwo(List<Student> stulist);
mapper部分代码
<select id="selectForeachOne" resultType="com.bjpowernode.domain.Student">
select * from student where id in
<foreach collection="list" item="myid" open="(" close=")" separator=",">
#{myid}
</foreach>
</select>
<select id="selectForeachTwo" resultType="com.bjpowernode.domain.Student">
select * from student where id in
<foreach collection="list" item="stu" open="(" close=")" separator=",">
#{stu.id}
</foreach>
</select>
.java部分代码
@Test
public void selectForeachOne() {
SqlSession sqlSession = MyBatisUntils.getSqlSession();
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
List<Integer> list = new ArrayList<>();
list.add(1001);
list.add(1002);
list.add(1003);
List<Student> students = mapper.selectForeachOne(list);
for (Student student : students) {
System.out.println(student);
}
}
@Test
public void selectForeachTwo() {
SqlSession sqlSession = MyBatisUntils.getSqlSession();
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
ArrayList<Student> students = new ArrayList<>();
Student s1 = new Student();
s1.setId(1001);
students.add(s1);
Student s2=new Student();
s2.setId(1002);
students.add(s2);
List<Student> students1 = mapper.selectForeachTwo(students);
for (Student student : students1) {
System.out.println(student);
}
sql代码片段 就是服用一些代码
步奏
1.先定义 sql 语句,表名,字段等
2.再使用