Mybatis批量插入返回成功的数目实例

网友投稿 1055 2023-02-26

Mybatis批量插入返回成功的数目实例

Mybatis批量插入返回成功的数目实例

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(List 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 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了,原来这个返回的值放进了入参的那个对象中。

数据库字段:

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:怎么在电脑上打开小程序(怎么在电脑上打开小程序软件)
下一篇:vue可以开发小程序(vue开发小程序自定义属性失效)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~