本文主要是介绍mybatis主表与明细表一对多的同时插入操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
对主表(采购申请表)和明细表(申请物资表)同时进行插入操作insert:
<!--对申请主表插入一条记录 --> <insert id="save" parameterType="com.bootdo.purchase.domain.ApplyDo" useGeneratedKeys="true" keyProperty="applyId">INSERT INTO pur_apply(apply_no,apply_depart_id,apply_person_id,apply_date,apply_estiamount,apply_status)VALUES(#{applyNo},(SELECT dept_id FROM mat_department WHERE dept_name = #{deptName} ),(SELECT sta_id FROM mat_staff WHERE sta_name = #{staName} ),#{applyDate},#{applyEstiAmount},#{applyStatus})<selectKey keyProperty="applyId" resultType="Integer" order="AFTER">SELECT LAST_INSERT_ID()</selectKey> </insert>
以上注:useGeneratedKeys="true" keyProperty="applyId" 或 <selectKey keyProperty="applyId" resultType="Integer" order="AFTER"> SELECT LAST_INSERT_ID() </selectKey>,可获取数据表中的自增的apply_id存放在持久类ApplyDo中的属性名applyId,applyId也是明细表对应主表的外键,对应持久类ApplyItemDo中的属性名itemApplyId.
<!--对明细表插入单条记录 --> <insert id="saveDetail" parameterType="com.bootdo.purchase.domain.ApplyItemDo" >INSERT INTO pur_apply_detail(item_apply_id,item_name,item_type,item_number,item_unit,item_estiprice,item_purpose,item_demdate,item_remake)VALUES(#{itemApplyId},#{itemName},#{itemType},#{itemNumber},#{itemUnit},#{itemEstiprice},#{itemPurpose},#{itemDemdate},#{itemRemake}) </insert>
ApplyServiceImpl.java:
@Autowired public ApplyDao applyDao; @Override public int save(ApplyDo applyDo) {//主表插入一条记录int count = applyDao.save(applyDo);int count2 = 0;int applyId = applyDo.getApplyId();//明细表插入多条记录for(ApplyItemDo items : applyDo.getItemDoList() ){items.setItemApplyId(applyId);count2 = applyDao.saveDetail(items);}return count2; }
这篇关于mybatis主表与明细表一对多的同时插入操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!