Spring Boot学习笔记18——数据访问(整合mybatis)

1. 环境准备

1.1 创建项目

创建一个新的项目(选中web、jdbc、mysql和mybatis环境)
Spring Boot学习笔记18——数据访问(整合mybatis)_第1张图片项目新增的mybatis依赖

<dependency>
       <groupId>org.mybatis.spring.bootgroupId>
       <artifactId>mybatis-spring-boot-starterartifactId>
       <version>2.1.3version>
dependency>

查看依赖树
Spring Boot学习笔记18——数据访问(整合mybatis)_第2张图片


1.2 整合mybatis步骤

  1. 配置数据源相关属性(详细见上一学习笔记Druid)

    • 加入依赖

      
      
      <dependency>
          <groupId>com.alibabagroupId>
          <artifactId>druidartifactId>
          <version>1.1.8version>
      dependency>
      

      如果后面启动有报log4j的错误,就加上log4j的依赖

      
      <dependency>
      	<groupId>log4jgroupId>
      	<artifactId>log4jartifactId>
      	<version>1.2.17version>
      dependency>
      
    • 配置yml

      spring:
      datasource:
      #   数据源基本配置
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
      type: com.alibaba.druid.pool.DruidDataSource
      # 追加配置,使得这两个sql文件能顺利执行
      schema:
      - classpath:sql/department.sql
      - classpath:sql/employee.sql
      initialization-mode: always
      #springboot2.x以上需要加这一句配置,不然无法执行sql和建表
      
      #   数据源其他配置
      initialSize: 5
      minIdle: 5
      maxActive: 20
      maxWait: 60000
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,log4j
      maxPoolPreparedStatementPerConnectionSize: 20
      useGlobalDataSourceStat: true
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
      
      
    1. 创建数据源配置类
      @Configuration
      public class DruidConfig {
               
      
      @ConfigurationProperties(prefix = "spring.datasource")
      @Bean
      public DataSource druid(){
               
      	return  new DruidDataSource();
      }
      
      //配置Druid的监控
      //1、配置一个管理后台的Servlet
      @Bean
      public ServletRegistrationBean statViewServlet(){
               
      ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
      Map<String,String> initParams = new HashMap<>();
      
      initParams.put("loginUsername","admin");
      initParams.put("loginPassword","123456");
      initParams.put("allow","");//默认就是允许所有访问
      initParams.put("deny","192.168.15.21");
      
      bean.setInitParameters(initParams);
      return bean;
      }
      
      
       //2、配置一个web监控的filter
      @Bean
      public FilterRegistrationBean webStatFilter(){
               
      FilterRegistrationBean bean = new FilterRegistrationBean();
      bean.setFilter(new WebStatFilter());
      
      Map<String,String> initParams = new HashMap<>();
      initParams.put("exclusions","*.js,*.css,/druid/*");
      
      bean.setInitParameters(initParams);
      
      bean.setUrlPatterns(Arrays.asList("/*"));
      
      return  bean;
      	}
      }
      
  2. 创建数据库
    Spring Boot学习笔记18——数据访问(整合mybatis)_第3张图片

    copy两个sql语句到resources的sql文件夹中
    Spring Boot学习笔记18——数据访问(整合mybatis)_第4张图片
    sql内容如下
    Spring Boot学习笔记18——数据访问(整合mybatis)_第5张图片Spring Boot学习笔记18——数据访问(整合mybatis)_第6张图片
    运行项目,见表成功
    表

  3. 创建JavaBean
    bean.Department
    Spring Boot学习笔记18——数据访问(整合mybatis)_第7张图片
    bean.Employee
    Spring Boot学习笔记18——数据访问(整合mybatis)_第8张图片 然后把yml中的schema配置给注释掉


2. 注解版mybatis

2.1 mybatis

  1. 创建mapper.DepartmentMapper接口,写sql语句方法

    @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);
    
    @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);
    }
    

    @Options(useGeneratedKeys = true,keyProperty = "id")是为了获取自增的id

  2. 创建控制器方法controller.DeptController

    @RestController
    public class DeptController {
           
    
    @Autowired
    DepartmentMapper departmentMapper;
    
    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id){
           
        return departmentMapper.getDeptById(id);
    }
    
    @GetMapping("/dept")
    public Department insertDept(Department department){
           
        departmentMapper.insertDept(department);
        return department;
    }
    }
    
  3. 启动项目,在浏览器进行添加操作
    Spring Boot学习笔记18——数据访问(整合mybatis)_第9张图片
    添加成功
    Spring Boot学习笔记18——数据访问(整合mybatis)_第10张图片


2.2 自定义MyBatis的配置规则

如果我们把数据库中departmentName改成department_name,这时进行查询将无法读取部门们,这时候就需要我们给容器中添加一个ConfigurationCustomizer,来解决列名改成驼峰命名法而导致无法读取内容的问题

创建config.MyBatisConfig

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

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

            @Override
            public void customize(Configuration configuration) {
     
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}
2.2.1 @MapperScan

注解版mybatis需要在每个mapper接口上添加@Mapper注解才能运行,但是我们直接在主启动类上添加 @MapperScan(value = "mapper接口所在的全限定名称包"),如@MapperScan(value="com.sb.mapper"),就可以省去给每个mapper接口写注解啦


3. 配置版mybatis

  1. 创建mapper接口mapper.EmployeeMapper

    public interface EmployeeMapper {
           //记得要用@Mapper或@MapperScan将接口扫描装配到容器中
    
    	public Employee getEmpById(Integer id);
    
    	public void insertEmp(Employee employee);
    }
    
  2. 创建mapper映射文件和全局配置文件
    Spring Boot学习笔记18——数据访问(整合mybatis)_第11张图片
    EmployeeMapper.xml

    <mapper namespace="com.sb.mapper.EmployeeMapper">
    
    <select id="getEmpById" resultType="com.sb.bean.Employee">
        SELECT * FROM employee WHERE id=#{id}
    select>
    
    <insert id="insertEmp">
        INSERT into employee(lastName,email,gender,d_id) values (#{lastName},#{email},#{gender},#	{dId})
    insert>
    
    mapper>
    

    mybatis-config.xml

    <configuration>
    
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    settings>
        
    configuration>
    
  3. 在yml追加mybatis配置

    mybatis:
    # 指定全局配置文件的位置
    config-location: classpath:mybatis/mybatis-config.xml
    # 指定sql映射文件的位置
    mapper-locations: classpath:mybatis/mapper/*.xml
    
  4. 创建控制器方法controller.EmpController

    @RestController
    public class EmpController {
           
    
    @Autowired
    EmployeeMapper employeeMapper;
    
    @GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id")Integer id){
           
        return employeeMapper.getEmpById(id);
    	}
    
    }
    
  5. 运行(记得现在employee表中先添加数据)
    Spring Boot学习笔记18——数据访问(整合mybatis)_第12张图片

注解法和配置法的mybatis可以共存


该SpringBoot学习笔记学习自雷神前辈,是对知识点的整理和自我认识的梳理,如有不当之处,欢迎指出

你可能感兴趣的:(spring,boot,自学,数据库,mybatis,spring,java,spring,boot)