Spring Boot 学习(8) springboot 整合 Mybatis

写在前面:最近利用晚上的时间在网上看视频学习Spring Boot,这博客是对学习的一点点总结及记录,技术是开源的、知识是共享的
如果你对Spring Boot 感兴趣,可以关注我的动态,我们一起学习。用知识改变命运,让家人过上更好的生活


源码地址https://github.com/zhangxycg/springboot-mybatis

点我直接查看源码

一、搭建开发环境

工程的目录结构如下图所示:

在这里插入图片描述

1. 创建数据库表

注:我在做的时候是用配置文件的形式自动创建的

department 表

CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `department_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

employee 表

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lastName` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `gender` int(2) DEFAULT NULL,
  `d_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

2. 导入需要的依赖

pom.xml

	<!-- Spingboot相关jar包版本 -->
	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
	<dependencies>
        <!-- springboot与JDBC整合包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>

        <!-- 标识web应用 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--springboot与mybatis的整合包-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <!-- mysql 驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- 引入druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

3. 编写数据源的相关配置

application.yml

spring:
  datasource:
    # 数据源基本配置
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot_mybatis?serverTimezone=GMT%2B8
    type: com.alibaba.druid.pool.DruidDataSource
    # 数据源其他配置
    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,slf4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500


#    initialization-mode: always
#    schema:
#      - classpath:sql/department.sql
#      - classpath:sql/employee.sql

编写一个配置类,将数据源引入过来

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return  new DruidDataSource();
    }

    // 配置Druid的监控
    // 配置一个管理后台的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","");//默认就是允许所有访问

        bean.setInitParameters(initParams);
        return bean;
    }


    // 配置一个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;
    }
}

二、利用注解的形式整合

1. 编写实体类

Employee

public class Employee {

    private Integer id;      // 员工id
    private String lastName; // 员工姓名
    private Integer gender;  // 员工性别
    private String email;    // 员工邮箱
    private Integer dId; 	 // 部门id

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

Department

public class Department {

    private Integer id;				// 部门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;
    }
}

2. 编写 Mapper接口层

DepartmentMapper

@Mapper // 指定这是一个操作数据库的mapper,将接口扫描到容器中
public interface DepartmentMapper {

    /**
     * 查询
     *
     * @param id
     * @return
     */
    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);

    /**
     * 新增
     *
     * @param department
     * @return
     */
    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("Insert into department(department_name) values(#{departmentName})")
    public int insertDept(Department department);

    /**
     * 更新
     *
     * @param department
     * @return
     */
    @Update("update department set department_name=#{departmentName} where id=#{id}")
    public int updateDept(Department department);
}

3. 编写 Controller 层

DeptController

@RestController
public class DeptController {

    @Autowired
    DepartmentMapper departmentMapper;

    /**
     * 根据id进行查询
     *
     * @param id
     * @return
     */
    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id) {
        return departmentMapper.getDeptById(id);
    }

    /**
     * 新增部门信息
     *
     * @param department
     * @return
     */
    @GetMapping("/dept")
    public Department insertDept(Department department) {
        departmentMapper.insertDept(department);
        return department;
    }
}

在不写配置文件的情况 自定义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);
            }
        };
    }
}

4. 测试

插入一条数据

在这里插入图片描述
查询刚才插入的数据

在这里插入图片描述

去数据库表表里面查询,数据插入进去了
在这里插入图片描述

二、利用配置文件的形式整合

1. 编写 Mapper 接口层

EmployeeMapper

@Mapper
public interface EmployeeMapper {

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    public Employee getEmpById(Integer id);

    /**
     * 新增员工信息
     *
     * @param employee
     */
    public void insertEmp(Employee employee);
}

2. 编写全局配置文件

mybatis-config.xml

<?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>

3. 编写 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.zxy.springboot.mapper.EmployeeMapper">

    <!-- 根据id查询员工信息 -->
    <select id="getEmpById" resultType="com.zxy.springboot.pojo.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>

4. 在 application.yml 中进行相关配置

mybatis:
  # 全局配置文件的位置
  config-location: classpath:mybatis/mybatis-config.xml
  # mapper 映射文件的位置
  mapper-locations: classpath:mybatis/mapper/*.xml

5. 编写 Controller 层

Controller

@RestController
public class EmpController {

    @Autowired
    EmployeeMapper employeeMapper;

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id") Integer id) {
        return employeeMapper.getEmpById(id);
    }

    /**
     * 新增员工信息
     *
     * @param employee
     * @return
     */
    @GetMapping("/emp")
    public Employee insertEmp(Employee employee) {
        employeeMapper.insertEmp(employee);
        return employee;
    }
}

6. 测试

在这里插入图片描述


由于水平有限,本博客难免有不足,恳请各位大佬不吝赐教!

发布了81 篇原创文章 · 获赞 1443 · 访问量 20万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 鲸 设计师: meimeiellie

分享到微信朋友圈

×

扫一扫,手机浏览