这篇文章将为大家详细讲解有关利用Mybatis怎么插入返回成功的数目,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

环境:
postgresql 9.6.5
spring 4.1
mybatis3
junit4
log4j
ThesisMapper.xml:
insert into public.thesis (name) values ( #{t.name} )
Mapper.java 借口:
public interface ThesisMapper {
int insertList(List thesisList);
} 服务类:
ThesisService:
public int insertList(ListthesisList) 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 thesisList = new ArrayList();
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
返回结果既为所求.
源码地址:
https://github.com/timo1160139211/trans
补充:关于Mybatis的insert方法返回值(将返回值受影响条数改为插入后的自增主键id)
今天做ssm项目的时候有一个这样的需求——我借阅一本书然后生成一条借阅记录(借阅记录的主键是递增的“borrowNum”),然后将这条记录的主键返回,在往上查阅资料后知道,只要在对应的xml文件对应的那个方法加上两个属性就行了,代码如下:
insert into t_borrow (userAccount, bookInfoNum,borrowTime, giveBackTime) values (#{useraccount,jdbcType=VARCHAR},#{bookinfonum,jdbcType=INTEGER}, #{borrowtime,jdbcType=DATE}, #{givebacktime,jdbcType=DATE})
就是加入的这三个属性:
useGeneratedKeys="true" keyProperty="borrownum" keyColumn="borrowNum"
Mybatis 配置文件 useGeneratedKeys 参数只针对 insert 语句生效,默认为 false。当设置为 true 时,表示如果插入的表以自增列为主键,则允许 JDBC 支持自动生成主键,并可将自动生成的主键返回。
“keyProperty”的值对应入参的字段名,“keyColumn”的值对应数据库表中的列名。

入参字段:

但是我们想接收这个返回的id的时候却不是我们想要的
int i=borrowMapper.insert(borrow);
我们得到的还是受影响的条数而不是返回的borrownum的值,那我们返回的borrownum去哪里了呢?在这里:我们的入参是不是一个borrow?
int mun=borrow.getBorrownum();
这个返回的mun就是我们要的borrownum了,原来这个返回的值放进了入参的那个对象中。
数据库字段:

关于利用Mybatis怎么插入返回成功的数目就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。