- 数据库ID字段要设置成自增
- 由于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)
- 接口
public interface TeacherMapper extends BaseMapper<Teacher> {
}
接口需要继承baseMapper<T>
- 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() 就好
网友评论