栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

springboot(三)与数据库打交道

springboot(三)与数据库打交道

1.整合JDBC 1.1导入JDBC所需的jar包

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


    mysql
    mysql-connector-java
    runtime

1.2在springboot配置文件中编写jdbc配置
spring:
  datasource:
    username: root
    password: 123456789
    url: jdbc:mysql://localhost:3306/mybatis?serverTimeone=UTC&userUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

在我们做完配置后,会自动生成datasource数据源对象。我们可以通过该对象获取数据库的连接(获取connection)。

1.3测试(查看数据源)

在我们做完配置后,会自动生成datasource数据源对象。我们可以通过该对象获取数据库的连接(获取connection)。

@SpringBootTest
class Springboot04DataApplicationTests {
    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() throws Exception{
    //通过数据源对象来获取数据库连接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }
}

结果:

HikariProxyConnection@501261420 wrapping
 com.mysql.cj.jdbc.ConnectionImpl@4d1f1ff5

可以看到这里我们使用的数据源使用的是Hikari,实现使用的是jdbc。

1.4JdbcTemplate

在我们配置好jdbc后,spring会帮我们生成一个JdbcTemplate对象,这个对象包含了对数据库进行操作的所有方法(增删改查)。想要使用它的话需要先进行自动装配。

package com.joker.controller;

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.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class jdbcController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @GetMapping("/userList")
    public List> userList() {
        String sql = "select * from user";
        List> list_maps = jdbcTemplate.queryForList(sql);
        return list_maps;
    }

    @GetMapping("/addUser")
    public String addUser() {
        String sql = "insert into mybatis.user(id,name,pwd) values (3,'lele','123456')";
        jdbcTemplate.update(sql);
        return "ok";
    }

    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id) {
        String sql = "update mybatis.user set name=?,pwd=? where id=" + id;
        Object[] objects = new Object[2];
        objects[0] = "xiaoming";
        objects[1] = "zzzzzzz";
        jdbcTemplate.update(sql, objects);
        return "ok";
    }

    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable int id) {
        String sql = "delete from user where id = ?";
        jdbcTemplate.update(sql, id);
        return "ok";
    }
}
2.整合druid 2.1导入依赖
//有关jdbc的也需要加上

    com.alibaba
    druid
    1.2.7

//使用log4j是因为这个数据源会自带日志监控功能,我们想要使用它就必须导入该依赖

    log4j
    log4j
    1.2.17

2.2配置文件

在使用默认的数据源的时候,我们可以看到spring使用的是Hikari,我们可一使用druid来作为数据源。

spring:
  datasource:
    username: root
    password: 123456789
    url: jdbc:mysql://localhost:3306/mybatis?serverTimeone=UTC&userUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    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,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
2.3测试(查看数据源)
@SpringBootTest
class Springboot04DataApplicationTests {
    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() throws Exception{
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }
}

运行结果:

com.mysql.cj.jdbc.ConnectionImpl@100c8b75
2021-10-09 16:50:25.233  INFO 868 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closing ...
2021-10-09 16:50:25.237  INFO 868 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closed

结果:此时数据源已经切换到druid,具体实现仍然是jdbc。

2.4编写配置类

主要目的是想要使yml配置文件中有关druid的配置生效,并使用后台监控功能。

package com.joker.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 {
    //将该配置绑定到yml文件中,必须要有这个注解
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }


    //后台监控功能
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        //后台需要有人登陆,配置账号密码
        HashMap initParameters = new HashMap<>();

        //增加配置,key是固定的			loginUsername loginPassword是固定的
        initParameters.put("loginUsername", "joker");
        initParameters.put("loginPassword", "123456");

        //允许谁能防问		allow也是固定的,参数为空表示所有人否能访问,也能写具体的人的ip,localhost表示本机才能访问
        initParameters.put("allow", "");

        bean.setInitParameters(initParameters);//设置初始化参数
        return bean;
    }
}
3.整合mybatis 3.1依赖导入
		
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.2.0
        
3.2配置数据库连接
#连接数据库
spring.datasource.username=root
spring.datasource.password=123456789
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#整合mybatis
mybatis.type-aliases-package=com.joker.pojo
#        classpath指的是resources目录。    这里相当于注册mapper
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

需要自己写实体类和接口,注意要在接口上加上@Mapper注解

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

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

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