Bootstrap

Mybatis新增记录后自动返回新增记录的id

@Controller
@EnableScheduling
@RequestMapping("student")
@Api(tags = "操作student数据库!")
public class StudentController {

    @Autowired
    StudentService studentService;
    // 插入数据库操作
    @ApiOperation("插入一条数据哦!")
    @RequestMapping("insert")
    @ResponseBody
    public int insert(@RequestBody StudentVO studentVO){
        int result = studentService.insert(studentVO);
        return result;
    }
@Service
public class StudentService extends ServiceImpl<StudentDao, StudentVO> implements IStudentService {

    @Autowired
    StudentDao studentDao;

    @Override
    public int insert(StudentVO studentVO){
        // 此处的id是操作数据库后,受影响的行数。请不要以这个作为返回!!!!
        int id = studentDao.insert(studentVO);
        
        // 此处以 studentVO.getId() 即可返回增加记录的id
        return studentVO.getId();
    }

}
@Mapper
public interface StudentDao extends BaseMapper<StudentVO> {
    //@Insert("INSERT INTO student(id,name,sex) VALUES(#{id}, #{name}, #{sex})")
    int insert(StudentVO studentVO);
}

注意:在xml文件中,对应的方法上要加上以下属性:

useGeneratedKeys="true" keyProperty="id" 
	<insert id="insert" parameterType="com.example.demo.vo.StudentVO"
			useGeneratedKeys="true" keyProperty="id"
			 >
		INSERT INTO
		student(id,name,sex)
		VALUES
		(#{id}, #{name}, #{sex})
	</insert>

按照上述操作,即可返回增加记录的i

;