55.SpringBoot学习笔记–SpringData-整合MyBatis-注解版MyBatis
注解版 MyBatis
demo.yangxu.springboot.mapper.DepartmentMapper
package demo.yangxu.springboot.mapper;
import demo.yangxu.springboot.bean.Department;
import org.apache.ibatis.annotations.*;
//指定这是一个操作数据库的mapper
@Mapper
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);
//useGeneratedKeys = true使用自动生成的主键
//keyProperty = "id" Department中的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);
}
demo.yangxu.springboot.controller.DeptController
package demo.yangxu.springboot.controller;
import demo.yangxu.springboot.bean.Department;
import demo.yangxu.springboot.mapper.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DeptController {
@Autowired
DepartmentMapper departmentMapper;
@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;
}
}
访问以下网址进行测试:
http://localhost:8080/dept?departmentName=AA
http://localhost:8080/dept/1
自定义 MyBatis 的配置规则,给容器中添加一个 ConfigurationCustomizer
demo.yangxu.springboot.config.MyBatisConfig
package demo.yangxu.springboot.config;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
使用 MapperScan 批量扫描所有的 Mapper 接口
demo.yangxu.springboot.Springboot05DataMybatisApplication
package demo.yangxu.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan(value = "demo.yangxu.springboot.mapper")
@SpringBootApplication
public class Springboot05DataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot05DataMybatisApplication.class, args);
}
}
###