关于useGeneratedKeys获取自增主键
场景描述:
一级菜单和二级菜单通过外键关联,在添加一级菜单同时添加二级菜单时,将一级菜单的主键id值作为二级菜单外键id值
问题解决:
可通过mybatis在insert后通过useGeneratedKeys获取一级菜单自增主键,在添加二级菜单时作为外键id值继续存入二级菜单
Java Bean
/** * 一级列表名称 * @author xj */ @Entity @Getter @Setter @Table(name = "tb_top_type") public class TopType extends BaseEntity implements Serializable { /** * 类型主键id */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id",unique = true) private Long id; /** * 一级列表名称 */ @Column(name = "top_type_name", unique = true) private String topTypeName; /** * 一级列表创建时间 */ @Column(name = "top_type_ctime", unique = true) private String topTypeCtime; /** * 关联二级菜单 */ private List<ProductType> types; }
@Entity @Getter @Setter @Table(name = "tb_type") public class ProductType extends BaseEntity implements Serializable { /** * 类型主键id */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id",unique = true) private Long id; /** * 类型名称 */ @Column(name = "type_name", unique = true) private String typeName; /** * 类型创建时间 */ @Column(name = "type_ctime", unique = true) private String typeCtime; /** * 类型修改时间 */ @Column(name = "type_uptime", unique = true) private String typeUptime; /** * 外键id */ @Column(name = "top_type_id", unique = true) private Long topTypeId; /** * 商品集合 */ private List<Product> products; }
@Slf4j @RestController @RequestMapping("/api/topType") @Api(tags = "一级菜单列表服务") public class TopTypeController extends BaseController{ @Autowired private ITopTypeService service; /** * 保存菜单列表信息 * @param topType * @return AjaxReslut */ @ApiOperation(value = "保存菜单列表信息",notes = "传入菜单列表信息") @RequestMapping(value ="/add",method = RequestMethod.POST) public AjaxResult add(@RequestBody TopType topType){ topType.setTopTypeCtime(DateUtils.nowTime()); return service.add(topType); } }
Service层:
@Service @Slf4j @Transactional public class TopTypeServiceImpl implements ITopTypeService { @Autowired private ITopTypeMapper mapper; @Autowired private IProductTypeMapper typeMapper; @Override public AjaxResult add(Object o) { try { /** 一级菜单*/ TopType topType = (TopType) o; int rows = mapper.add(topType); if (rows<0){ return AjaxResult.error("添加一级菜单失败!"); } /** 二级菜单*/ List<ProductType> types = topType.getTypes(); types.stream().forEach( productType->productType.setTopTypeId(topType.getId()) ); if (null != types) { typeMapper.addList(types); } return AjaxResult.success("添加成功"); } catch (Exception e) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); log.error("添加菜单信息失败:" + e.getMessage()); return AjaxResult.error("添加失败:" + e.getMessage()); } } }
mapper层
<!-- 保存菜单信息 --> <insert id="add" parameterType="TopType" useGeneratedKeys="true" keyProperty="id" > INSERT INTO tb_top_type( top_type_name, top_type_ctime ) VALUES( #{topTypeName}, #{topTypeCtime} ) </insert>
一定要注意useGeneratedKeys keyProperty 保证主键id是自动增长的