mybatis plus主键回填

2020-05-26  本文已影响0人  墨明棋妙_6ba9
  1. 数据库ID字段要设置成自增
  2. 由于mybatis plus默认生成的主键是long,要在实体类中设置
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;

import java.util.List;

@Data
public class Teacher {
    @TableId(value = "id",type = IdType.AUTO)
    private Integer id;

    private String name;

    //使用collection,否则直接resultType 导致student查询出为null。
    private List<Student> students;
}

注意 @TableId(value = "id",type = IdType.AUTO)

  1. 接口
public interface TeacherMapper  extends BaseMapper<Teacher> {
}

接口需要继承baseMapper<T>

  1. controller
 @PostMapping("/insertTeacher")
    public RespBean InsertStudent(@RequestBody Teacher teacher){
        int i = teacherMapper.insert(teacher);
        if(i==1){
            System.out.println(teacher.getId());
            return RespBean.ok("插入成功");
        }
        return RespBean.error("插入失败");
    }

注意insert 后主键会自动 set 到实体的 ID 字段,所以你只需要 getId() 就好

上一篇下一篇

猜你喜欢

热点阅读