Mybatis批量插入返回影响的行数
环境:
- postgresql 9.6.5
- spring 4.1
- mybatis3
- junit4
- log4j
ThesisMapper.xml:
<!-- 批量插入 -->
<insert id="insertList" parameterType="java.util.List">
insert into public.thesis
(name)
values
<foreach collection="list" item="t" index="index" separator=",">
(
#{t.name}
)
</foreach>
</insert>
Mapper.java 借口:
public interface ThesisMapper {
int insertList(List<Thesis> thesisList);
}
服务类:
ThesisService:
public int insertList(List<Thesis> thesisList) throws Exception {
return thesisDao.insertList(thesisList);
}
测试父类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-mvc.xml", "classpath:spring-mybatis.xml" })
@WebAppConfiguration
public class BaseTest {
@Autowired
protected WebApplicationContext wac;
@Test
public void test() {}
}
测试类:
public class UserOpsTest extends BaseTest {
@Autowired
private ThesisService ts;
@Test
public void insertListTest() {
List<Thesis> thesisList = new ArrayList<Thesis>();
Thesis t1 = new Thesis();
Thesis t2 = new Thesis();
Thesis t3 = new Thesis();
t1.setName("qq1");
t2.setName("ww2");
t3.setName("asd");
thesisList.add(t1);
thesisList.add(t2);
thesisList.add(t3);
try {
System.out.println(ts.insertList(thesisList));
} catch (Exception e) {
e.printStackTrace();
}
}
}
日志输出:
[DEBUG] ==> Preparing: insert into public.thesis ( name) values ( ? )
[DEBUG] ==> Parameters: qq1(String), ww2(String), asd(String)
[DEBUG] <== Updates: 3
3
返回结果既为所求.