雷丰阳springboot之数据访问mybatis

[TOC]

雷丰阳课件

image-20210501180311668
image-20210501180335661
image-20210501180404403
image-20210501180425324
image-20210501180446133

引入mybatis

需要在pom文件当中添加下面的starts:

        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.1
        

利用ide分析一下pom文件的依赖关系:

image-20210502140842082

得到下面的依赖关系,这个就是mybatis官方出品的starters的依赖关系:

image-20210502141103773

整合druid数据源

在使用mybatis之前,我们还使用druid数据源。

整合进来吧。

在pom文件当中添加:

        
        
        
            com.alibaba
            druid
            1.1.8
        

复制原来的配置文件

image-20210502141616316

新建数据库

image-20210502141538077

编写配置类

编写配置类,将数据源正确配置过来。

package com.atguigu.springboot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@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 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 initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));

        return  bean;
    }
}

启动测试一下,看druid数据源的管理控制台,能不能够进来。

image-20210502142212950

证明数据源的配置是没有什么问题的。

数据库当中建表

建表,使用雷丰阳提供的sql文件:

image-20210502142338912

利用之前学过的知识,把sql文件放到resources当中的sql文件夹下面:

image-20210502142507241

要想让程序启动的时候,就运行这两个sql文件,只需要在application.yaml当中配置schema相关的配置就可以了:

image-20210502142604280

重新启动我们的程序,就发现在数据库当中已经创建了相关的表了:

image-20210502142800452

创建javabean封装表的数据

创建两个javabean,一个是Employee,一个是Department。

package com.atguigu.springboot.bean;

public class Employee {

    private Integer id;
    private String lastName;
    private Integer gender;
    private String email;
    private Integer dId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getdId() {
        return dId;
    }

    public void setdId(Integer dId) {
        this.dId = dId;
    }
}

package com.atguigu.springboot.bean;

public class Department {

    private Integer id;
    private String departmentName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
}

mybatis操作数据库(注解版)

写一个mapper,然后将sql语句,都写在注解上,按照注解的方式来操作数据库,如下图所示:

image-20210502144044039
    package com.atguigu.springboot.mapper;

import com.atguigu.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);

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

写一个controller测试一下:

package com.atguigu.springboot.controller;

import com.atguigu.springboot.bean.Department;
import com.atguigu.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 getDepartment(@PathVariable("id") Integer id){
        return departmentMapper.getDeptById(id);
    }

    @GetMapping("/dept")
    public Department insertDept(Department department){
        departmentMapper.insertDept(department);
        return department;
    }
}

运行程序之后,然后插入一条数据:

image-20210502145845851

看一下数据库当中的内容:

image-20210502145907731

然后再执行查询的操作:

image-20210502150008176

总结

如果我们想要在springboot当中使用mybatis,只需要引入mybatis,然后写一个mapper,用@Mapper注解加入进来就可以了。

非常简单的。

我们不需要做任何配置,都是自动配置好了的。

我们可以通过ctrl+n来搜索:MybatisAutoConfiguration

在这个里面都自动配置好了,很多的东西。

注解版小问题

image-20210502150404360
image-20210502150556337

重新运行程序,然后测试:

image-20210502150713603

成功解决这个问题。


驼峰小问题

image-20210502150907010

如果现在把数据库表当中的departmentName字段名字,修改成为department_name

然后把程序当中的mapper接口当中 的表的列名,也都修改正确,修改成为下面的样子:

image-20210502151141059

重启程序,然后使用查询测试一下:

image-20210502151237462

departmentName就已经查不出来了。

在这种情况下是:javabean的属性名字是叫做departmentName,但是数据库表的列名是叫做department_name

以前有配置文件的情况下,我们可以开启驼峰命名法来兼容这个问题。

没有配置文件的时候,我们怎么做呢?

我们可以查看mybatis的autoconfiguration当中是怎么写的。

image-20210502151540085

我们发现在MybatisAutoConfiguration当中给IOC容器注入SqlSessionFactory这个bean的时候,里面有一个ConfigurationCustomizer。

在没有配置文件的时候,我们写一个mybatis的配置类,用一下这个ConfigurationCustomizer。

image-20210502151944996

重启我们的程序,然后再次进行测试。

image-20210502152037766

问题解决。

使用自定义mybatis的配置规则。

给容器当中添加一个:ConfigurationCustomizer,就可以了。

mapper批量扫描问题

如果我们的mapper特别多,我们给每个mapper文件都加上@Mapper注解,好麻烦哦。

我们可以这样做,在主程序上面添加@MapperScan这样的注解:

image-20210502152428611

mybatis操作数据库(配置版)

实际开发当中,我们也经常使用配置文件的方式。

我们需要一个mybatis的全局配置文件。

每一个mapper,我们写一个sql映射文件。

先写一个mapper

image-20210502152929022

创建配置文件

image-20210502153420277

创建mybatis的全局配置文件mybatis-config.xml,然后创建mapper的sql映射文件:EmployeeMapper.xml

这些配置文件怎么写呢?

我们可以去查阅mybatis的官方文档。

mybatis源代码都是托管在了github上面的,我们可以去github上面查看mybatis的官方文档的:

https://mybatis.org/mybatis-3/getting-started.html

下面的这个部分,就是全局配置文件的内容:

image-20210502153555463



  
    
      
      
        
        
        
        
      
    
  
  
    
  

下面的这个部分,就是sql映射文件的内容:

image-20210502153656886



  

编写sql映射配置文件




    
    

    
        INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
    


mybatis配置文件和全局配置文件关联

image-20210502154406431

测试一下

image-20210502160028651

上面dId没有值,是因为,我们的全局配置文件当中,没有开启驼峰命名法:

我们在全局文件当中进行如下的配置:




    
        
    

然后重新测试一下:

image-20210502160226410

总结

在springboot当中,我们是可以复合使用注解版和配置版的。配置版的核心步骤,就是在application.yml当中指定mybatis的全局配置文件和sql映射文件。

你可能感兴趣的:(雷丰阳springboot之数据访问mybatis)