Mybatis-Plus gets the auto-increment primary key ID after inserting data

Problem: After inheriting BaseMapeer and adopting the built-in insert, the number of successfully inserted items is returned, and the ID of the auto-incrementing primary key cannot be obtained

=======MAPPER=======
@Mapper
@Repository
public interface StudentMapper extends BaseMapper<Student> {
}

====Entity=========
public class Student {

    private Integer id;

    private String name;

    private Integer age;
    
}
=======Service=======
@Service
public class StudentServiceImpl implements StudentService {

@Override
public int saveStudent(Student student) {
    return studentMapper.insert(student);
}
}

 Use the save method instead

First set the auto-increment primary key in the entity class, and then extends

=======MAPPER=======
@Mapper
@Repository
public interface StudentMapper extends BaseMapper<Student> {
}

====Entity=========
public class Student {

    @TableId(type = IdType.AUTO)
    private Integer id;

    private String name;

    private Integer age;
    
}
=======Service=======
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper,Student> implements StudentService {

@Override
public int saveStudent(Student student) {
    boolean res = save(student);
    if(!res){log.error("插入失败");
    //此时getId就能拿到主键了
    Integer sid = student.getId();
    return student;
}
}

Guess you like

Origin blog.csdn.net/qq_40421671/article/details/131221760