springboot整合数据库

springboot整合数据库

整合jdbc

  1. 依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
  2. 配置
    spring:
      datasource:
        username: root
        password: 123456
        url: jdbc:mysql://localhost:3306/mybatis?userUnicode=true&characterEncoding=utf-8
        driver-class-name: com.mysql.cj.jdbc.Driver
  3. controller实现CRUD
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @RequestMapping("userlist")
    public List<Map<String, Object>> list() {
        String sql = "select * from user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    
    @RequestMapping("add")
    public String addUser() {
        String sql = "insert into mybatis.user(id,name,pwd) values (5,'王五','123456')";
        int update = jdbcTemplate.update(sql);
        return "update";
    }
    
    @RequestMapping("update/{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] = "野原新之助";
        objects[1] = "8848";
        int update = jdbcTemplate.update(sql, objects);
        return "update";
    }
    
    @RequestMapping("delete/{id}")
    public String deleteUser(@PathVariable("id") int id) {
        String sql = "delete from mybatis.user where id=?";
        int update = jdbcTemplate.update(sql, id);
        return "delete";
    }

整合druid

springboot默认使用hikari作为数据源,但也可以使用其他数据源,只需要修改配置文件中spring.datasource.type屬性即可

  1. 依赖

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.21</version>
    </dependency>
  2. application配置文件
    spring:
      datasource:
        username: root
        password: 123456
        url: jdbc:mysql://localhost:3306/mybatis?userUnicode=true&characterEncoding=utf-8
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
    
        #Spring Boot 默认是不注入这些属性值的,需要自己绑定
        #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,stat:监控统计、log4j:日志记录、wall:防御sql注入
        #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
        #则导入 log4j 依赖即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j
        filters: stat,wall,log4j
        maxPoolPreparedStatementPerConnectionSize: 20
        useGlobalDataSourceStat: true
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  3. druid配置
    @Configuration
    public class DruidConfig {
    
        @ConfigurationProperties(prefix = "spring.datasource")
        @Bean
        public DataSource druidDataSource(){
            return new DruidDataSource();
        }
    
        //后台监控
        @Bean
        public ServletRegistrationBean statViewServlet(){
            ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
            //管理配置
            HashMap<String, String> hashMap = new HashMap<>();
            //增加配置
            hashMap.put("loginUsername", "admin");
            hashMap.put("loginPassword", "123456");
            //访问等级v值为空时所有人都能访问,localhost为限本机访问
            hashMap.put("allow", "");
            bean.setInitParameters(hashMap);//初始化参数
            return bean;
        }
    }

整合mybatis

  1. 依赖

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.1</version>
    </dependency>
  2. 配置
    spring:
      datasource:
        username: root
        password: 123456
        url: jdbc:mysql://localhost:3306/mybatis?userUnicode=true&characterEncoding=utf-8
        driver-class-name: com.mysql.cj.jdbc.Driver
    
    mybatis:
      type-aliases-package: cn.pinked.pojo
      mapper-locations: classpath:mybatis/mapper/*.xml
  3. UserMapper接口
    @Mapper
    @Repository
    public interface UserMapper {
        List<User> queryUserList();
        User queryUserById(int id);
        int addUser(User user);
        int updateUser(User user);
        int deleteUser(int id);
    }
  4. UserMapper.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="cn.pinked.mapper.UserMapper">
    
        <select id="queryUserList" resultType="User">
            select * from mybatis.user
        </select>
    
        <select id="queryUserById" resultType="User">
            select * from mybatis.user where id = #{id}
        </select>
    
        <insert id="addUser" parameterType="User">
            insert into mybatis.user (id, name, pwd) values (#{id}, #{name}, #{pwd});
        </insert>
    
        <update id="updateUser" parameterType="User">
            update mybatis.user set name = #{name}, pwd = #{pwd} where id = #{id};
        </update>
    
        <delete id="deleteUser">
            delete from mybatis.user where id = #{id}
        </delete>
    
    </mapper>
  5. service层
  6. controller层

原文地址:https://www.cnblogs.com/pinked/p/12367541.html

时间: 2024-08-30 14:45:37

springboot整合数据库的相关文章

SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统

1.前言本文主要介绍使用SpringBoot与shiro实现基于数据库的细粒度动态权限管理系统实例. 使用技术:SpringBoot.mybatis.shiro.thymeleaf.pagehelper.Mapper插件.druid.dataTables.ztree.jQuery 开发工具:intellij idea 数据库:mysql.redis 2.表结构还是是用标准的5张表来展现权限.如下图:image 分别为用户表,角色表,资源表,用户角色表,角色资源表.在这个demo中使用了mybat

小D课堂【SpringBoot】数据库操作之整合Mybaties和事务讲解

========================8.数据库操作之整合Mybaties和事务讲解 5节课================================ 加入小D课堂技术交流答疑群:Q群:699347262 1.SpringBoot2.x持久化数据方式介绍 简介:介绍近几年常用的访问数据库的方式和优缺点 1.原始java访问数据库 开发流程麻烦 1.注册驱动/加载驱动 Class.forName("com.mysql.jdbc.Driver") 2.建立连接 Connec

springboot整合mybatis(SSM开发环境搭建)

0.项目结构: 1.application.properties中配置整合mybatis的配置文件.mybatis扫描别名的基本包与数据源 server.port=80 logging.level.org.springframework=DEBUG #springboot mybatis #jiazai mybatis peizhiwenjian mybatis.mapper-locations = classpath:mapper/*Mapper.xml mybatis.config-loca

springboot 整合jdbcTemplate

springboot 整合jdbcTemplate 〇.搭建springboot环境(包括数据库的依赖) 一.添加依赖 如果导入了jpa的依赖,就不用导入jdbctemplete的依赖了jpa的依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency&g

SpringBoot系列十二:SpringBoot整合 Shiro

1.概念:SpringBoot 整合 Shiro 2.具体内容 Shiro 是现在最为流行的权限认证开发框架,与它起名的只有最初的 SpringSecurity(这个开发框架非常不好用,但是千万不要 以为 SpringSecurity 没有用处,它在 SpringCloud 阶段将发挥重大的作用).但是现在如果要想整合 Shiro 开发框架有一点很遗憾, SpringBoot 没有直接的配置支持,它不像整合所谓的 Kafka.Redis.DataSource,也就是说如果要想整合 Shiro 开

SpringBoot整合Kafka和Storm

前言 本篇文章主要介绍的是SpringBoot整合kafka和storm以及在这过程遇到的一些问题和解决方案. kafka和storm的相关知识 如果你对kafka和storm熟悉的话,这一段可以直接跳过!如果不熟,也可以看看我之前写的博客.一些相关博客如下. kafka 和 storm的环境安装 地址:http://www.panchengming.com/2018/01/26/pancm70/ kafka的相关使用 地址:http://www.panchengming.com/2018/01

SpringBoot整合Jsp和Thymeleaf (附工程)

前言 本篇文章主要讲述SpringBoot整合Jsp以及SpringBoot整合Thymeleaf,实现一个简单的用户增删改查示例工程.事先说明,这两个是单独整合的,也就是两个工程.如需其中一个,只需看相应部分的介绍即可.若需工程源代码,可以直接跳到底部,通过链接下载工程代码. SpringBoot整合Jsp 开发准备 环境要求 JDK: 1.7或以上 SQL: MySql 这里我们需要在mysql中建立一张用户表,用于存储用户的信息. 数据库脚本如下: CREATE TABLE `t_user

springboot整合Quartz实现动态配置定时任务

前言 在我们日常的开发中,很多时候,定时任务都不是写死的,而是写到数据库中,从而实现定时任务的动态配置,下面就通过一个简单的示例,来实现这个功能. 一.新建一个springboot工程,并添加依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency>

SpringBoot整合集成redis

Redis安装:https://www.cnblogs.com/zwcry/p/9505949.html 1.pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http: