话不多说直接上代码:
主表:GoodShelf、副表:pallets
主表上加上:useGeneratedKeys="true" keyProperty="id" ,id为主键名称,省略不重要的代码
<insert id="insertSelective" parameterType="com.ljb.entity.GoodShelf" useGeneratedKeys="true" keyProperty="id">
insert into T_GOODSHELF
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
Id,
</if>
...
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
...
</trim>
</insert>
插入代码
public String add(GoodShelf goodshelf) throws Exception{
...
result = goodShelfMapper.insertSelective(goodshelf);//保存
...
Pallet pallet = new Pallet();
...
pallet.setGoodshelfkey(goodshelf.getId());//获取刚保存的主表主键
pallets.add(pallet);
...
result = palletMapper.insertPallerBatch(pallets);//批量保存箱信息
...
return str;
}
以上注:useGeneratedKeys="true" keyProperty="主键列名" 或 <selectKey keyProperty="applyId" resultType="Integer" order="AFTER"> SELECT LAST_INSERT_ID() </selectKey>,可获取数据表中的自增的"主键列名"存放在持久类中的属性名"主键列名","主键列名"也是明细表对应主表的外键