SpringBoot连接数据库

本文详细介绍了SpringBoot中如何连接并使用数据库,包括JDBC、Druid监控、MyBatis的配置与使用,以及自定义MyBatis配置规则实现字段名自动转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot连接数据库

1、jdbc

spring:
  datasource:
    username: root
    password: qwe123
    url: jdbc:mysql://8.129.166.53/testdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
#    指定是否初始化
#    initialization-mode: always
#    指定后缀data/schema-xxxx.sql
#    platform: xxxx
#    运行建表语句;
#    schema:
#      - classpath:schema-department.sql

效果:

​ 默认是用class com.zaxxer.hikari.HikariDataSource作为数据源;

​ 数据源的相关配置都在DataSourceProperties里面;

2、DataSourceInitializer:ApplicationListener

​ 作用:

​ 1)、createSchema();运行建表语句;

​ 2)、initSchema();运行插入数据的sql语句;

默认只需要将文件命名为:

默认规则:建表:schema-${platform}.sql 数据:data-${platform}.sql
可以使用   
	schema:
      - classpath:department.sql
      # 指定位置文件
  platform: department
      # 指定文件后缀,会默认寻找schema/data-department.sql文件
      #    指定是否初始化
#    initialization-mode: always
#    指定后缀data/schema-xxxx.sql
#    platform: xxxx
#    运行建表语句;
#    schema:
#      - classpath:schema-department.sql

3、JDBC的使用

@Controller
public class MyJdbc {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @ResponseBody
    @RequestMapping("/hello")
    public Map<String, Object> hello(){
        List<Map<String,Object>> list = jdbcTemplate.queryForList("select * from department");
        return list.get(0);
    }
}

4、使用druid的监控

配置druid

spring:
  datasource:
    username: root
    password: qwe123
    url: jdbc:mysql://8.129.166.53/testdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    type: com.alibaba.druid.pool.DruidDataSource

#   执行数据库文件
#    指定是否初始化
#    initialization-mode: always
#    指定后缀data/schema-xxxx.sql
#    platform: xxxx
#    运行建表语句;
#    schema:
#      - classpath:schema-department.sql

    #   数据源其他配置
#    初始化大小,最小,最大
    initialSize: 5
    minIdle: 5
    maxActive: 20
#    配置获取连接等待超时的时间(毫秒)
    maxWait: 60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    timeBetweenEvictionRunsMillis: 60000
    # 配置有一个连接在连接池中的最小生存时间,单位是毫秒
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    # 打开PSCache,指定每个连接上PSCache的大小
    poolPreparedStatements: true
    #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,slf4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    # 通过connectProperties属性来打开mergeSql功能,慢SQL记录
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

package com.example.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.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {

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

    //配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String,String> initParams = new HashMap<>();
        //排除的文件资源
        initParams.put("exclusions","*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");

        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }

    //配置Druid监控
    //1、配置一个管理后台的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","qwe123");
        initParams.put("allow","");//空白允许所有
        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }

}

5、Mybatis

步骤:

​ 1)、配置数据源相关属性(见上一节Druid)

​ 2)、给数据库建表

​ 3)、创建JavaBean

1)、注解版

//指定这是一个操作数据库的mapper
@Component//交给IOC容器管理
@Mapper
public interface DepartmentMapper {

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

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

    @Options(useGeneratedKeys = true,keyProperty = "id")//标识自动增长
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);
}

问题:

自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer;

使得_转换为驼峰命名:user_name会自动转为userName

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){

            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}
使用MapperScan批量扫描所有的Mapper接口,也可以在Config配置上使用;
@MapperScan(value = "com.atguigu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
	}
}

2)、配置文件版

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

由于指定了全局配置文件,之前我们设置的转换驼峰命名被覆盖失效,需用xml配置

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
@RestController
public class DeptController {

    @Autowired
    DepartmentMapper departmentMapper;

    @Autowired
    EmployeeMapper employeeMapper;

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

    @GetMapping("/dept")
    public Department insertDept(Department department){
        departmentMapper.insertDept(department);
        return department;
    }

    @GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id") Integer id){
        return employeeMapper.getEmpById(id);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值