mybatis返回插入的主键id值(mysql数据库)

使用MyBatis往MySQL数据库插入一条记录后如果需要返回该条记录的自增主键值,可以用一下方法。
1,在mapper中指定keyProperty属性,如下所示,指定了keyProperty="id",其中id表示插入StockFee的主键值。xml代码

<insert id="insertStockFee" parameterType="com.***.***.****.***.entity.StockFee" useGeneratedKeys="true" keyProperty="id">
<![CDATA[
INSERT INTO stock_fee(uid,orderNo,amount,share,platformFee,buyCharge,netValue,productCode,payStatus,createTime,lastModTime)
VALUES(#{uid},#{orderNo},#{amount},#{share},#{platformFee},#{buyCharge},#{netValue},#{productCode},#{payStatus},#{createTime},#{lastModTime})
]]>
</insert>

2,StockFee.java

public class StockFee implements Serializable{
/**
* serialVersionUID
*/
private static final long serialVersionUID = -3788366959323844085L;
/**
* 主键id
*/
private int id;
/**
* 用户id
*/
private int uid;
/**
* 订单编号
*/
private String orderNo;
//set and get 方法
}


3,StockFeeDao.java

@Repository("stockFeeDao")
public class StockFeeDao extends BaseDao{
@Autowired
private StockFeeMapper stockFeeMapper;

public int insertStockFee(StockFee stockFee){
stockFeeMapper.insertLicaiStockFee(stockFee);
return stockFee.getId();
}
}

4,测试

@Autowired
private StockFeeService stockFeeService
@Test
public void insertLicaiGuYingBao(){
StockFee stockFee = new StockFee();
stockFee.setUid(2147483640);
stockFee.setOrderNo("p9456745532234005");
stockFee.setAmount(1203);
stockFee.setShare(3000.3423);
stockFee.setPlatformFee(1234320);
stockFee.setBuyCharge(123410);
stockFee.setNetValue(1234.21);
stockFee.setProductCode("1009002343");
stockFee.setPayStatus(0);
stockFee.setCreateTiidme(new Date());
stockFee.setLastModTime(new Date());
System.out.println(MessageFormat.format("output:id={0}",stockFee.getId()));
int id = stockFeeService.insertLicaiStockFee(stockFee);
System.out.println(MessageFormat.format("output:id={0}",id));
}

运行结果:
output:id=0
output:id=65
假如StockFeeDao.java改为:

public int insertStockFee(StockFee stockFee){
return stockFeeMapper.insertLicaiStockFee(stockFee);
}

再运行刚才的单元测试返回的是1,这表示插入成功的sql条数。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值