springboot 整合Mybatis步骤(注解版)

注解的好处:

①不需要专门书写mapper的xml文件,直接在接口的方法上书写SQL语句,因此也不用配置xxxmapper.xml文件的地址

②注解的方式,不需要为实体类配置别名

1.搭建项目,导入web、jdbc、Mybatis、MySQL依赖

2.在配置文件中配置数据源datasource相关属性

spring:
  datasource:
    username: root
    password: admin
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

(可以将默认的jdbc连接池更改为Druid连接池并配置相关属性)

详情参考配置Druid数据源

3.建立数据库和数据表

4.创建与表对应的bean类(department类,有id和departmentName属性)

5.创建mapper接口,在接口上加上mapper注解

如果mapper比较多,可以批量扫描,【 在主配置类上加@Mapper(value="mapper接口所在包") 】


@Mapper
public interface DepartmentMapper {

    @Select("select * from mybatis.department where id = #{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from mybatis.department where id = #{id}")
    public int deleteDeptById(Integer id);

    @Insert("insert into mybatis.department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id = #{id}")
    public int updateDept(Department department);

}

6.创建三层结构逐层调用(这里简化一下,直接controller调用mapper)

@RestController
public class DeptController {

    @Autowired
    DepartmentMapper departmentMapper;

    //根据部门id查询部门
    @GetMapping("dept/{id}")
    public Department getDeptById(@PathVariable("id") Integer id){
        return departmentMapper.getDeptById(id);
    }
    //增加部门
    @GetMapping("dept")
    public Department insertDept(Department department){
        departmentMapper.insertDept(department);
        return department;
    }
    //删除部门
    @GetMapping("dept/{id}")
    public int deleteDeptById(@PathVariable("id") Integer id){
        return departmentMapper.deleteDeptById(id);
    }
    //修改部门
    @GetMapping("dept")
    public Department updateDept(Department department){
        departmentMapper.updateDept(department);
        return department;
    }
    
}

扩展一下(自定义Mybatis配置规则)

如果数据库中的字段名是department_name,而bean类的字段名是departmentName,这种时候可以添加一个配置类配置一下mybatis开启驼峰命名法映射规则,设置configuration.setMapUnderscoreToCamelCase(true);

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){
            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值