美文网首页
mybatis plus主键回填

mybatis plus主键回填

作者: 墨明棋妙_6ba9 | 来源:发表于2020-05-26 12:39 被阅读0次
    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() 就好

    相关文章

      网友评论

          本文标题:mybatis plus主键回填

          本文链接:https://www.haomeiwen.com/subject/tkddahtx.html