栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot学习笔记(二)——集成持久层框架JDBC、Mybatis

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot学习笔记(二)——集成持久层框架JDBC、Mybatis

上周学习了SpringBoot项目的基本结构已经配置文件的一些使用,其实不用特意去记住这些配置及内容,只是需要学习一下有这样一个印象,当工作中有疑惑的时候能够有思路,能够想到解决问题的原因就可以了,这篇文章更是如此,这篇文章我会列一下我在工作中常用的SpringBoot集成框架,并将一些内容简单讲解,当我们工作中发现项目也集成了该框架,我们可以第一时间知道这个框架是用来做什么的,甚至直接可以拿来使用就最好不过了,介绍到此结束,接下来开始正文。

SpringBoot集成JDBC

1.导入依赖

		
			org.springframework.boot
			spring-boot-starter-web
		


		
			org.springframework.boot
			spring-boot-starter-jdbc
		

2.配置文件

server:
  port: 8000

jdbc:
  driver-class-name: com.mysql.cj.jdbc.Driver #Mysql 6以上的版本使用com.mysql.cj.jdbc.Driver,Mysql 6以下版本使用com.mysql.jdbc.Driver
  username: 用户名
  password: "密码"
  #Mysql地址,后面为连接信息配置,不用改变
  url: jdbc:mysql://数据库服务器IP/阿里云数据库则为云地址:端口号/数据库名称?autoReconnect=true&useUnicode=true&characterEncoding=UTF8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&allowMultiQueries=true

3.JDBC创建Bean对象

package com.springBoot.helloworld.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;


@Configuration
public class MyJdbcTemplate {
    @Value("${jdbc.driver-class-name}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public JdbcTemplate myFirstJdbcTemplate(){
        DriverManagerDataSource dataSource=new DriverManagerDataSource();
        dataSource.setDriverClassName(this.driverClassName);
        dataSource.setUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.setQueryTimeout(1000);
        return jdbcTemplate;
    }
}

4.JDBC使用

package com.springBoot.helloworld.controller.test1;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class springBootController {

    // 使用JDBC需要根据名称注入对应的依赖,注意名称要使用添加Bean注解的方法名称
    @Autowired
    private JdbcTemplate myFirstJdbcTemplate;

    @GetMapping("/index")
    public String test() {
        String sql = "select * from student";
        System.out.println(myFirstJdbcTemplate.queryForList(sql));
        return "helloworld";
    }
}

使用这种方式就可以进行JDBC的连接了,我只尝试了连接Mysql数据库,如果需要连接其他的数据库,例如Oracle、SqlServer等数据库的话,还是需要小伙伴们自行尝试哈。

我们也可以这样使用,这是在我项目中的使用方式,就是将JDBC数据库的连接信息统一放在spring-dataSource配置下。

此时的配置文件为:

server:
  port: 8000

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver #Mysql6以上的版本使用com.mysql.cj.jdbc.Driver,Mysql6以下版本使用com.mysql.jdbc.Driver
    username: 用户名
    password: "密码"
    #Mysql地址,后面为连接信息配置,不用改变
    url: jdbc:mysql://数据库服务器IP/阿里云数据库则为云地址:端口号/数据库名称?autoReconnect=true&useUnicode=true&characterEncoding=UTF8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&allowMultiQueries=true
    jdbc:
      driver-class-name: com.mysql.cj.jdbc.Driver #Mysql6以上的版本使用com.mysql.cj.jdbc.Driver,Mysql6以下版本使用com.mysql.jdbc.Driver
      username: 用户名
      password: "密码"
      #Mysql地址,后面为连接信息配置,不用改变
      url: jdbc:mysql://数据库服务器IP/阿里云数据库则为云地址:端口号/数据库名称?autoReconnect=true&useUnicode=true&characterEncoding=UTF8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&allowMultiQueries=true

JDBC的Java配置文件为:

package com.springBoot.helloworld.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;


@Configuration
public class MyJdbcTemplate {
    // value注解添加 spring.datasource 前缀
    @Value("${spring.datasource.jdbc.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.jdbc.url}")
    private String url;
    @Value("${spring.datasource.jdbc.username}")
    private String username;
    @Value("${spring.datasource.jdbc.password}")
    private String password;

    @Bean
    public JdbcTemplate myFirstJdbcTemplate(){
        DriverManagerDataSource dataSource=new DriverManagerDataSource();
        dataSource.setDriverClassName(this.driverClassName);
        dataSource.setUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.setQueryTimeout(1000);
        return jdbcTemplate;
    }
}

这样做的好处就在于将数据库连接信息全部放在spring.datasource下面,方便统一管理。

一般我们在工作中使用Mybatis去连接数据库,更有新的工程是使用Mybatis-Plus强化Mybatis的功能,不太会使用JDBC了,但是JDBC会用于我们的项目可能需要连接多个数据库的时候使用

SpringBoot整合Druid数据库连接池

Druid连接池是阿里出品的,功能十分强大,下面简单给大家介绍一个小功能,你就能看出他的强大了,首先第一步还是导入依赖。

		
			com.alibaba
			druid
			1.2.1
		

第二步编写配置文件

server:
  port: 8000

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver #Mysql6以上的版本使用com.mysql.cj.jdbc.Driver,Mysql6以下版本使用com.mysql.jdbc.Driver
    username: 用户名
    password: "密码"
    #Mysql地址,后面为连接信息配置,不用改变
    url: jdbc:mysql://数据库服务器IP/阿里云数据库则为云地址:端口号/数据库名称?autoReconnect=true&useUnicode=true&characterEncoding=UTF8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&allowMultiQueries=true
#   配置类型为Druid数据库连接池
    type: com.alibaba.druid.pool.DruidDataSource
    # 初始化大小
#    initialization: 5
#    minIdle: 5
#    maxActive: 20
#    maxWait: 60000
#    timeBetweenEvictionRunsMillis: 60000
#    minEvictableIdleTimeMillis: 300000
#    validationQuery: SELECt 1 FROM DUAL
#    testWhileIdle: true
#    testOnBorrow: false
#    testOnReturn: false
#    poolPreparedStatements: true
#    配置监控统计拦截的过滤器:stat监控统计、wall防御SQL注入、log4j日志记录
#    使用log4j需要导入依赖,导入后修改该键值对为filters:stat,wall,log4j
    filters: stat,wall
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;durid.stat.slowSqlMillis=500

如果监听时需要log4j日志记录则导入依赖(我测试过了,添加log4j没有什么大的变化,哈哈,尤其是今年年初log4j爆出了安全漏洞,比较抵触,但是个人练习用的话没什么问题)

		
			log4j
			log4j
			1.2.17
		

第三步是编写Java配置类

package com.springBoot.helloworld.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.HashMap;


@Configuration
public class DruidConfig {

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

    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        // 配置后台SQL管理页面,访问localhost:端口号/druid/即访问
        ServletRegistrationBean bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid
// 需要添加Mapper注解表明是一个mapper接口
// 也可以不添加此注解,在启动类上添加@MapperScan("com.springBoot.helloworld.mapper")注解
// @MapperScan可以指定扫描的包同样可以实现此效果
@Mapper
public interface StudentMapper {

    public List queryMyList();
}

2-2编写XML文件






    
        select name, age, class as myClass from student
    

3.编写配置文件

使用mybatis的时候不需要过多的配置,只需要配置mapper接口与XML文件的映射关系

# 表示mybatis会在如下两个路径中查询对应的XML文件,超出此范围则查询不到
mybatis:
  mapper-locations:
    - classpath:mapper*Mapper.xml  #表示匹配resource目录下的mapper目录下的所有目录下的所有Mapper.xml结尾的文件
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  #表示打印SQL执行的log日志

如果不配置就会发生org.apache.ibatis.binding.BindingException报错。

到这里就可以自由使用Mybatis了,下面给小伙伴推荐一下以往的Mybatis的文章,供大家学习借鉴,如果有问题的话随时可以私信问我哦。

Mybatis中使用list作为参数进行In查询

Mybatis使用Map作为参数或返回值进行查询

我工作时的项目选择的是Mybatis-Plus作为持久层的框架,Mybatis-Plus是Mybatis的强化版,有兴趣或有时间的小伙伴们,我建议也去学习一下,完整版教学这里放上链接↓

Mybatis-Plus在工作中的使用

最后推荐几个我在工作中感觉比较好用的Mybatis的小插件

1.Mybatis Builder

这个插件的用处很小,但很精妙

使用这个插件以后,我们的mapper接口与xml文件的旁边就会生成一个绿色的箭头,此时我们就可以点击箭头进行mapper接口与xml文件的跳转,个人感觉很好用,用过才知道。

2.Mybatis log

 这个插件需要在网上下载后自行导入,因为新版本的是需要收费的哈哈,这个到底有多好用呢?

如果没有这个插件,我们想看一下真实执行的SQL需要查看控制台

如果SQL有多个参数的时候就需要自己组装,但是这个插件会显示出完整的SQL打印内容

我们就可以直接复制出来使用了。

需要这个插件的小伙伴可以私聊我获取哈。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/781949.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号