整合springboot和mybatis的应用

整合MyBatis

1. 引入依赖

    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>2.1.2</version>
    </dependency>

2.配置数据源

使用druid数据源则参照文章

3.注解版:

@Mapper  //如果在主程序入口上加@MapperScan(value="mapper所在包")  可以批量扫描,不需要每个接口都加@mapper
public interface DepartmentMappers {

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

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

    //插入时,@Options注解可以将自增主键封装进去
    //useGeneratedKeys=true;   keyProperty="id" 封装对象哪个属性存放主键
}
@RestController
public class DeptController {

    @Autowired
    DepartmentMappers departmentMappers;

    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id ){
        return departmentMappers.getDeptById(id);
    }
}
使用自定义的方式配置Mybatis的规则

开启驼峰命名法的映射规则:

@Configuration
public class MybatisConfig {
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        }
    }
}

4.配置文件版

首先要在接口加入@Mapper

指定全局配置和sql映射文件的位置

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

配置完之后使用的方式和之前的一模一样

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值