SpringBoot之数据库访问(整合MyBatis)


前言

讲讲SpringBoot整合MyBatis的操作(其实还应该有整合JDBC和Druid的)

用到的MySQL数据库仍然运行在Linux上的


提示:以下是本篇文章正文内容,下面案例可供参考

一、MyBatis注解版

1.配置数据源相关属性(预备工作)

我们这里用到了yaml作配置文件,需分别配置 数据库基本属性,Druid基本属性,mybatis基本属性

先给出代码 :

spring:
  datasource:
    #   数据源基本配置
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://Linux服务器地址或本机地址:端口号/mybatis
    #数据源
    type: com.alibaba.druid.pool.DruidDataSource
    #   数据源其他配置(即Druid配置)
    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
    #mybatis配置
mybatis:
  config‐location: classpath:mybatis/mybatis‐config.xml 指定全局配置文件的位置
  mapper‐locations: classpath:mybatis/mapper/*.xml 指定sql映射文件的位置

2.搭建一个简易的MVC架构

(我这里没给出service层,而是由controller层直接调用mapper)
在这里插入图片描述
先不用管config包,这个我们后面会详细讲

3.编写mapper接口

我们以DepartmentMapper接口为例,注解版无需创建xml文件,直接在接口前打注解即可

我还是头一次用,真的很方便

public interface DepartmentMapper {
    
    

//注解内写上SQL语句
@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);

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

//设置主鍵自增
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into department(department_name)value(#{departmentName})")
public Integer insert(Department dept);
}

4.编写controller层

这里我们还是使用的REST风格 的前后端交互(没有严格实现,仅作实验使用)

@RestController
public class DepartmentController {
    
    
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    EmployMapper employeeMapper;

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

    @GetMapping("/dept")
    public Integer insertDepartment(Department department){
    
    
        departmentMapper.insert(department);
        return 1;
    }
}

在我们用地址?属性名=属性值向后台插入数值的时候,可以观察到Linux中数据库的值添加进来了,这就说明插入成功了(查询同理 )

5.超简单的驼峰命名法统一字段名与属性名

前面提到的config包就在这里起作用了
我们需要先创建一个MyBatisConfig类 ,编写一个返回值为ConfigurationCustomizer的方法

@Configuration
public class MyBatisConfig {
    
    
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
    
    
        return new ConfigurationCustomizer() {
    
    
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
    
    
             	//开启驼峰命名
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

感觉这种写法有点诡异… 自己还是见识太少呀

使用配置类的方式省去了在每一个xml文件中都要加字段名转换的标签,非常高效

二、MyBatis配置版

1.创建全局配置类和SQL.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>
<?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">

<!--SQL文件与接口绑定-->
<mapper namespace="edu.cust.cs.mapper.EmployMapper">
    <select id="getEmpById" resultType="edu.cust.cs.bean.Employee">
        select * from employee where id=#{id}
    </select>

    <insert id="insert">
        insert into employee(id,lastName,email,gender,d_id)value(#{id},#{lastName},#{email},#{gender},#{dId})
    </insert>

</mapper>

2.其实我还没跑通代码…

在这里插入图片描述

代码如下(示例):

该处使用的url网络请求的数据。


总结

最后想写点昨晚上电工实验的感想

能在实验室中实现的东西,在实际的生产环境中,不一定适用. 这就是实验室阶段和生产阶段的不同之处. 实验室阶段的环境都是相当理想的环境, 而在生产过程中 , 条件更加复杂.

在实际开发中也一样, 开发环境与软件实际运行环境有着很大的差别, 在程序员的计算机上 , bug都是可调的. 而在用户设备上 ,情况一般更恶心人.

猜你喜欢

转载自blog.csdn.net/qq_45596525/article/details/109250824