您当前的位置: 首页 >  mybatis

white camel

暂无认证

  • 2浏览

    0关注

    442博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

SpringBoot——SpringBoot整合MyBatis(注解、XML配置)

white camel 发布时间:2020-04-27 13:18:29 ,浏览量:2

目录
  • 一、SpringBoot整合MyBatis
  • 二、Mybatis增删改查(使用注解方式)
  • 三、Mybatis增删改查(XML配置方式)

在这里插入图片描述

一、SpringBoot整合MyBatis

跳转到目录

引入依赖

    
        org.springframework.boot
        spring-boot-starter-jdbc
    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.mybatis.spring.boot
        mybatis-spring-boot-starter
        2.1.2
    
    
        com.alibaba
        druid-spring-boot-starter
        1.1.20
    
    
        mysql
        mysql-connector-java
        runtime
    
    
        org.springframework.boot
        spring-boot-starter-test
        test
        
            
                org.junit.vintage
                junit-vintage-engine
            
        
    

依赖关系 在这里插入图片描述

项目构建

1、在resources下创建department.sqlemployee.sql,项目启动时创建表(在数据库中自动生成)

schema:
  - classpath:sql/department.sql
  - classpath:sql/employee.sql

2、实体类

public class Department {
    private Integer id;
    private String departmentName;
 
 	// 省略 getter/setter 方法
}
public class Employee {
    private Integer id;
    private String lastName;
    private Integer gender;
    private String email;
    private Integer dId;
    
    // 省略 getter/setter 方法
}

3、配置文件

spring:
  datasource:
    username: root
    password: 1111
    url: jdbc:mysql://localhost:3306/springboot_mybatis
    driver-class-name: com.mysql.jdbc.Driver
    initialization-mode: always
    # 数据源更改为druid
    type: com.alibaba.druid.pool.DruidDataSource

    druid:
      # 连接池配置
      # 配置初始化大小、最小、最大
      initial-size: 1
      min-idle: 1
      max-active: 20
      # 配置获取连接等待超时的时间
      max-wait: 3000
      validation-query: SELECT 1 FROM DUAL
      test-on-borrow: false
      test-on-return: false
      test-while-idle: true
      pool-prepared-statements: true
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      filters: stat,wall,slf4j
      # 配置web监控,默认配置也和下面相同(除用户名密码,enabled默认false外),其他可以不配
      web-stat-filter:
        enabled: true
        url-pattern: /*
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        login-username: admin
        login-password: root
        allow: 127.0.0.1

    schema:
      - classpath:sql/department.sql
      - classpath:sql/employee.sql
二、Mybatis增删改查(使用注解方式)

跳转到目录

  • 创建mapper接口
/**
 * Description:
 *
 * @author zygui
 * @date 2020/4/17 16:10
 */
// 指定这是一个操作数据库的mapper
@Mapper // 这里必须要添加这个Mapper注解; 也可以在主启动类上统一通过@MapperScan(value="con.zy.mapper")来扫描
public interface DepartmentMapper {

    @Select("SELECT * FROM department WHERE id = #{id}")
    public Department getDeptById(@Param("id") Integer id);

    @Delete("DELETE FROM department WHERE id = #{id}")
    public int deleteDeptById(@Param("id") Integer id);

    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("INSERT INTO department(department_name) VALUES(#{departmentName})")
    public int insertDept(Department department);

    @Update("UPDATE department SET department_name = #{departmentName} WHERE id = #{id}")
    public int updateDept(Department department);
}
  • 创建Controller
@RestController
public class DeptController {

    @Resource
    private DepartmentMapper departmentMapper;

    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id) {
        return departmentMapper.getDeptById(id);
    }

    @GetMapping("/dept")
    public Department insertDept(Department department) {
        int count = departmentMapper.insertDept(department);
        if (count > 0) {
            System.out.println("插入数据成功");
        }
        return department;
    }
  • 访问:http://localhost:8080/dept?departmentName=gzy 添加一条数据

    访问:http://localhost:8080/dept/1获取数据

Mybatis配置

开启驼峰命名法

我们的实体类和表中的列名一致,一点问题也没有

我们把department表的departmentName列名改为department_name看看会发生什么

访问:http://localhost:8080/dept/1获取数据

[{“id”:1,“departmentName”:null}]

由于列表和属性名不一致,所以就没有封装进去,我们表中的列名和实体类属性名都是遵循驼峰命名规则的,可以开启mybatis的开启驼峰命名配置

# 开启驼峰映射
mybatis:
  configuration:
    map-underscore-to-camel-case: true

然后重启项目,重新插入数据,再查询就发现可以封装进去了

也可以通过向spring容器中注入org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer的方法设置mybatis参数

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

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {
                // 开启驼峰命名映射
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

在这里插入图片描述 在这里插入图片描述

Mapper扫描

使用@mapper注解的类可以被扫描到容器中,但是每个Mapper都要加上这个注解就是一个繁琐的工作,能不能直接扫描某个包下的所有Mapper接口呢,当然可以,在springboot启动类上加上@MapperScan

@MapperScan(“cn.clboy.springbootmybatis.mapper”)

三、Mybatis增删改查(XML配置方式)

跳转到目录

  • 创建mybatis全局配置文件




    
    
        
    

  • 创建EmployeeMapper接口
@Mapper 或者 @MapperScan将接口扫描装配到容器中
public interface EmployeeMapper {

    public Employee getEmpById(@Param("id") Integer id);

    public void insertEmp(Employee employee);
}
  • 创建EmployeeMapper.xml映射文件




    
        SELECT * FROM employee WHERE id = #{id};
    

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

  • 配置文件(application.yaml)中指定配置文件和映射文件的位置
# 加载mybati的全局配置文件
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
  • Controller
@RestController
public class EmpController {
	@Resource
    private EmployeeMapper employeeMapper;

    @GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id") Integer id) {
        return employeeMapper.getEmpById(id);
    }
}
  • 测试 在这里插入图片描述
关注
打赏
1661428283
查看更多评论
立即登录/注册

微信扫码登录

0.0387s