spring boot 2 配置并使用mybatis进行简单的数据库查询

14 篇文章 0 订阅
4 篇文章 0 订阅
  1. 在配置文件中引入mybatis依赖
<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>2.1.1</version>
</dependency>
  1. 设置一个yml文件,进行数据库连接的配置
    在这里插入图片描述
spring:
  datasource:
    #数据源基本配置
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springmybatis?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
    type: com.alibaba.druid.pool.DruidDataSource
    #数据源其它配置
  1. 设置mybaits的配置文件,自动扫描指定文件夹下的mapper
    在这里插入图片描述
package com.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//auto scan all mapper in specified folder
@MapperScan(value = "com.demo.mapper")
@SpringBootApplication
public class SpringmabatisApplication {

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

}

  1. 自定义一个mybatis配置类(非必须,可通过其它方式配置,下文有提出),设置允许mybatis进行字段模糊匹配
    在这里插入图片描述
package com.demo.config;

import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

//申明此文件为配置文件,此语句由mybatis提供,所以格式不一
@org.springframework.context.annotation.Configuration
public class MybatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {

            }
        };
    }

//    配置mybatis进行字段模糊匹配查询 setMapUnderscoreToCamelCase(true);
    public void customize(Configuration configuration){
        configuration.setMapUnderscoreToCamelCase(true);
    }

}

  1. 创建一个实体类,这里使用lombok设置了setter,getter
    在这里插入图片描述
package com.demo.bean;

import lombok.Data;

@Data
public class Department {
    private Integer id;
    private String departmentName;
}

  1. 创建对应实体类的mapper
    在这里插入图片描述
package com.demo.mapper;

import com.demo.bean.Department;
import org.apache.ibatis.annotations.*;

@Mapper
public interface DepartmentMapper {

    @Select("select * from department where id=#{id}")
    public Department getDepartmentById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int delectDepartmentById(Integer id);

//    options中表示获取数据库中自增属性,属性名为id
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDepartment(Department department);

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

}

  1. 设置关于实体类的controller,当用户访问时会从相应的controller进入到程序中
package com.demo.controller;

import com.demo.bean.Department;
import com.demo.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 DepartmentController {
    @Autowired
    DepartmentMapper departmentMapper;

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

启动项目,在浏览器中通过localhost:8080/depet/1访问第一个方式,通过localhost:8080/depet?departmentName=abc访问第二个方法

在第四步的时候,我们也可以通过另一种方法进行配置
a 在配置文件application.xml中设置以下内容
在这里插入图片描述

mybatis:
  #指定全局配置文件
  config-location: classpath:mybatis/mybatisConfig.xml
  #指定扫描特定目录sql映射文件
  mapper-locations: classpath:mybatis/mapper/*.xml

b 全局配置文件中内容如下,注意全局配置文件的存放位置
在这里插入图片描述

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
<!--        设置将下划线与驼峰命名进行匹配-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

c sql映射文件内容如下
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.demo.mapper.EmployeeMapper">

    <select id="getEmpById" resultType="com.demo.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>

千万注意配置文件中为<!DOCTYPE configuration
而在映射文件中为<!DOCTYPE mapper

d 在controller中同样的申明方法
在这里插入图片描述
e 而在mapper中则少去了sql语句的实现,因为相关功能被移动到了全局sql映射文件中进行实现
在这里插入图片描述
在地址栏输入相应的地址,访问相应的controller,与之前的功能实现一样。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值