SpringBoot整合MyBatis(注解)

一、引入相关jar

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

二、创建JavaBean

public class Department {
    private Integer id;
    private String departmentName;

    public Integer getId() {
        return id;
...

三、创建Mapper(注解版)的crud

//指定这是一个操作数据库的mapper
//@Mapper//不配置的话可以在启动类中使用@MapperScan全局配置
public interface DepartmentMapper {

    @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")
    @Insert("insert into department(departmentName) values(#{departmentName}) ")
    public int insertDept(Department department);

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

}

 如果不想每个mapper都配置@Mapper可以在启动类全局配置@MapperScan

@MapperScan(value = "com.zhq.springboot.mapper")
@SpringBootApplication
public class SpringbootDataMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootDataMybatisApplication.class, args);
    }

}

四、自定义Mybatis配置属性

可以自定义一个ConfigurationCustomizer然后添加到容器

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer myBatisConfigurationCustomizer( ){
        return new ConfigurationCustomizer(){

            @Override
            public void customize(Configuration configuration) {
                //开启驼峰命名
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

五、编写Controller测试是否配置成功

@RestController
public class DeptController {
    @Autowired
    DepartmentMapper departmentMapper;

    /**
     * 根据id查找
     * @param id
     * @return
     */
    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id){
        return departmentMapper.getDeptById(id);
    }

    /**
     * 新增
     * @param department
     * @return
     */
    @GetMapping("/dept")
    public Department insertDept(Department department){
        departmentMapper.insertDept(department);
        return department;

    }
}

猜你喜欢

转载自blog.csdn.net/xm393392625/article/details/88549534