使用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条数。