• 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层

  • 相关阅读:
    C连载20-转换说明中的异常
    Android连载30-SharedPreference存储
    搭建一个开源项目12-Kubernetes集群部署(下)以及elasticsearch部署
    JavaScript连载29-元素类型获取、节点CD
    从零开始学VUE之模板语法(计算属性)
    从零开始学VUE之模板语法(绑定属性)
    从零开始学VUE之模板语法(插值操作)
    从零开始学VUE之Vue的生命周期
    从零开始学VUE之Vue创建时可以传入的Option属性
    从零开始学VUE之Vuejs初体验(DEMO)
  • 原文地址:https://www.cnblogs.com/pinked/p/12367541.html
Copyright © 2020-2023  润新知