Springboot integrated database, druid background monitoring, integrated mybatis

Springboot's own datasource
import dependency and mysql dependency

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
             <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

You can now test the connection test in the test class

package com.jj.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class DemoApplicationTests {
    
    
@Autowired
    DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
    
    
        System.out.println("dataSource.getClass() = " + dataSource.getClass());
//        获取数据库连接
        Connection conn = dataSource.getConnection();
        System.out.println("dataSource.getConnection() = " + conn);
        conn.close();

    }

}

The test results can see that the default is Springboot's connection
yml configuration

# 数据源配置
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/op?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
    username: root
    password: 123456
    druid:
      # 初始连接数
      initialSize: 5
      # 最小连接池数量
      minIdle: 10
      # 最大连接池数量
      maxActive: 20
      # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      # 配置一个连接在池中最大生存的时间,单位是毫秒
      maxEvictableIdleTimeMillis: 900000
      # 配置检测连接是否有效
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      webStatFilter:
        enabled: true
      statViewServlet:
        enabled: true
      

Crud operation of the control layer

package com.jj.demo.Controller;

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

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

@RestController
public class JdbcController {
    
    
    @Autowired
    JdbcTemplate jdbcTemplate;
//    全查
    @RequestMapping("/viplist")
    public List<Map<String,Object>> show(){
    
    
        String sql="select * from vip";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        System.out.println("list = " + list);
        return list;
    }
//    添加
    @RequestMapping("/add")
    public String add(){
    
    
        String sql="insert into vip (name,pwd) values('娇娇','123456')";
        int update = jdbcTemplate.update(sql);
        System.out.println("update = " + update);
        return "ok";
    }
//    删除
    @RequestMapping("/del")
    public String del(){
    
    
        String sql="delete from vip where name='娇娇'";
        int update = jdbcTemplate.update(sql);
        System.out.println("sql = " + update);
        return "ok";
    }
//    修改
    @RequestMapping("/update")
    public String update(){
    
    
        String sql="update vip set name='冯娇娇' where pwd='123'";
        int update = jdbcTemplate.update(sql);
        System.out.println("update = " + update);
        return "ok";
    }
}

In Alibaba's connection pool, yml can be added to the type attribute.
Import dependencies

     <!--     druid 连接池   -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>

Run the test class to see that the current connection is Alibaba

2020-12-22 15:55:32.333  INFO 11524 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-12-22 15:55:32.813  INFO 11524 --- [           main] com.jj.demo.DemoApplicationTests         : Started DemoApplicationTests in 4.924 seconds (JVM running for 6.178)

dataSource.getClass() = class com.alibaba.druid.pool.DruidDataSource
dataSource.getConnection() = com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@447fa959

2020-12-22 15:55:32.933  INFO 11524 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2020-12-22 15:55:32.933  INFO 11524 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
 INFO [SpringContextShutdownHook] - {dataSource-1} closed

For other crud operations,
use druid for background monitoring,
create a new config class
Insert picture description here

package com.jj.demo.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 {
    
    
//    与我们的yml 连接起来
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
    
    
        return  new DruidDataSource();
    }
//    后台监控
    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
    
    
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
//        设置密码
        HashMap<String, String> map = new HashMap<>();
//        添加配置  登录的账号和密码是固定的
        map.put("loginUsername","admin");
        map.put("loginPassword","123456");
//        设置允许谁访问
        map.put("allow","");
//        也可以设置禁止谁访问
//        设置初始化参数
        bean.setInitParameters(map);
        return bean;
    }
//    过滤器的
    @Bean
    public FilterRegistrationBean webdilter(){
    
    
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
//        可以过滤那些请求
        HashMap<String, String> stringStringHashMap = new HashMap<>();
//        添加就可以了
//        那些buguolv
        stringStringHashMap.put("exclusions","*.js,*.css,/druid/*");
//        初始化参数
        bean.setInitParameters(stringStringHashMap);
        return bean;

    }
}

effect

Insert picture description here
Insert picture description here
You can see some background monitoring! ! !
**Integrate mybatis **
Import dependencies

<!--        mybatis 的包-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

Configure the yml of mybatis

#mybatis的配置
mybatis:
  configuration:
    #   sql日志显示,这里使用标准显示
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#    整合别名的包
    #  数据库中如果有类似 如  user_name 等命名,会将 _后的字母大写,这里是为了和实体类对应
  #    map-underscore-to-camel-case: true
  #  配置mapper文件的路径
  type-aliases-package: com.jj.demo.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml

The entity class I am a common id, name, pwd
interface
Insert picture description here
simple crud, interface and xml

package com.jj.demo.mapper;

import com.jj.demo.pojo.vip;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface Vipdao {
    
    
//    查
    List<vip> show();
//    删
    int del(int id);
//    改
    int update(vip vip);
//    增加
int insertvip(vip vip);
}

<?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.jj.demo.mapper.Vipdao">
<!--查-->
    <select id="show" resultType="vip">

        select * from vip
    </select>
<!--    删-->
    <delete id="del" parameterType="int">
        delete from vip where id=#{id}
    </delete>
<!--    改-->
    <update id="update" parameterType="vip">
        update vip set name=#{name} where id=#{id}

    </update>
<!--    添加-->
    <insert id="insertvip" parameterType="vip">
        insert into vip (name,pwd) values (#{name},#{pwd})
    </insert>
</mapper>

Control layer

package com.jj.demo.Controller;

import com.jj.demo.mapper.Vipdao;
import com.jj.demo.pojo.vip;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class mybatisController {
    
    
//    注入 不想写业务层了直接调用的dao 层
    @Autowired
    Vipdao vipdao;
//    全查
    @RequestMapping("/show")
    public List<vip> show(){
    
    
        List<vip> show = vipdao.show();

        return show;
    }
//删除
    @RequestMapping("/del1")
    public String del1(){
    
    
        int i = vipdao.del(36);
        return "ok";
    }
//    修改
    @RequestMapping("/up")
    public String up(){
    
    
        vip vip = new vip();
        vip.setName("冯娇娇");
        vip.setId(38);
        vipdao.update(vip);
        return "okk!";
    }
//    添加
    @RequestMapping("/ins")
    public String in(){
    
    
        vip vip = new vip();
        vip.setName("冯娇娇1");
        vip.setPwd("11111");
     vipdao.insertvip(vip);
        return "vip1";
    }
}

end!!!

Guess you like

Origin blog.csdn.net/m0_46937429/article/details/111559734