mybatis主表与明细表一对多的同时插入操作方法
马二科 人气:0对主表(采购申请表)和明细表(申请物资表)同时进行插入操作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; }
加载全部内容