整合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

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

猜你喜欢

转载自www.cnblogs.com/JIATCODE/p/13170018.html