参考:https://www.cnblogs.com/XuXiaoCong/p/18064633
pom引入包,启动器
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.xcg</groupId>
    <artifactId>webapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>webapp</name>
    <description>WebApp project for Spring Boot3</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

<!--        <dependency>-->
<!--            <groupId>com.mysql</groupId>-->
<!--            <artifactId>mysql-connector-j</artifactId>-->
<!--            <scope>runtime</scope>-->
<!--        </dependency>-->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>3.3.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-3-starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-3-starter</artifactId>
            <version>1.2.23</version>
        </dependency>

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

        <!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.4.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<!--        <dependency>-->
<!--            <groupId>org.apache.logging.log4j</groupId>-->
<!--            <artifactId>log4j-core</artifactId>-->
<!--            <version>2.23.1</version>-->
<!--        </dependency>-->

<!--        &lt;!&ndash; https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api &ndash;&gt;-->
<!--        <dependency>-->
<!--            <groupId>org.apache.logging.log4j</groupId>-->
<!--            <artifactId>log4j-api</artifactId>-->
<!--            <version>2.23.1</version>-->
<!--        </dependency>-->

        <!-- 使用SpringBoot自带的log组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>

        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>4.4.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.51</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.34</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.yml配置,注意数据库驱动版本,旧版本(Mysql5)的数据库驱动没有cj,MYSQL 5 驱动:com.mysql.jdbc.Driver,MYSQL 6+ 驱动:com.mysql.cj.jdbc.Driver
注:连接字符串中要指定时区serverTimezone,不然可能会报错 https://www.cnblogs.com/daemonFlY/p/9820541.html
GMT是格林威治标准时间的缩写,也叫“世界时”(World Time),用于表示全球协调的时间。
GMT+8表示在格林威治标准时间上加上8个小时,也就是UTC(Coordinated Universal Time)+8小时,代表了中国的东八区时区。
因此,GMT+8和GMT%2B8表示的都是同一个概念,即UTC+8小时的时区。
在URL中,一些特殊字符需要进行URL编码才能被网络传输,比如"+“这个符号。而”%2B"代表了"+"符号的编码。

server:
  port: 8100
spring:
  profiles:
    active: dev #表示开发环境,nacos config
  application:
    name: webapp
  # 数据源类型
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型
    # MYSQL 5 驱动:com.mysql.jdbc.Driver,MYSQL 6+ 驱动:com.mysql.cj.jdbc.Driver
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/xcgdb?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&autoReconnect=true&failOverReadOnly=false
    username: root
    password: root
    druid:
      # 连接超时时间,60000毫秒(1分钟)
      socket-timeout: 60000
      filter:
        stat:
          # 启动SQL语句监控,同时会影响其他面板中的SQL展示(如:影响"URI监控"中的jdbc数据)
          enabled: true
          # 数据库类型(实测没啥用,会自动根据上面的连接自动识别)
          db-type: mysql
          # 记录慢日志("SQL监控"面板中数值会标记为红色)
          log-slow-sql: true
          # 慢日志判定标准(单位:毫秒)
          slow-sql-millis: 3000
          # 自定义日志级别,默认日志级别"ERROR"
          slow-sql-log-level: ERROR
        wall:
          # 启用防火墙
          enabled: true
          # 数据库类型(实测没啥用,会自动根据上面的连接自动识别)
          db-type: h2
          config:
            # 是否允许DELETE操作(报错异常:java.sql.SQLException:sql injection violation, dbType mysql, druid-version 1.2.21, delete not allow : DELETE FROM ...)
            delete-allow: false
            # 是否允许DROP TABLE操作
            drop-table-allow: false
      initial-size: 5 #数据库连接池初始化连接数量
      min-idle: 5 #数据库连接池最小连接数量
      max-active: 20 #数据库连接池最大连接数量
      # 配置获取连接等待超时的时间 60000毫秒(1分钟)
      max-wait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位毫秒。
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小生存时间 300秒/5分钟
      min-evictable-idle-time-millis: 300000
      # Druid用来测试连接是否可用的SQL语句,默认值每种数据库都不相同。
      # 参考 https://www.jianshu.com/p/c9845884d735
      validation-query: SELECT 1 FROM DUAL
      # 空闲时测试连接是否可用
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      # 打开 PSCache,并且指定每个连接上 PSCache 的大小
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      # 配置监控统计拦截的 Filter,去掉后监控界面 SQL 无法统计,wall 用于防火墙 stat,wall,log4j
      filters: stat,wall
      # 通过 connection-properties 属性打开 mergeSql 功能;慢 SQL 记录
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      # 合并多个DruidDataSource的监控数据
      useGlobalDataSourceStat: true
      # 配置 DruidStatFilter Web应用/URI监控/Session监控
      web-stat-filter:
        # 启用"Web应用/URI监控/Session监控"面板
        enabled: true
        # 监控这里指定的路径
        url-pattern: /*
        # 过滤路径
        exclusions: /druid/*,*.js,*.gif,*.jpg,*.png,*.css,*.ico,*.html,*.json
        # "Session监控"面板设置(RestFul纯后端没有session)
        session-stat-enable: true
        session-stat-max-count: 1000
        principal-session-name: xxc
        principal-cookie-name: xxc
        profile-enable: true
      # 配置 DruidStatViewServlet
      stat-view-servlet:
        # 启用Druid监控面板
        enabled: true
        # 面板路径(默认"/druid/*")(Druid已做了处理,不会被自定义过滤器拦截)
        url-pattern: /druid/*

        # 使用Nginx转发导致访问IP丢失,allow、deny均失效,可将allow设置为 192.168.0.0/16,10.0.0.0/8 允许所有请求,注意使用账号保护
        # IP 白名单,没有配置或者为空,则允许所有访问
        # allow: 127.0.0.1
        # IP 黑名单,若白名单也存在,则优先使用
        # deny: 192.168.31.253

        # 禁用 HTML 中 Reset All 按钮
        # 面板上的重置按钮(禁用后面板上重置按钮依然会显示和互动,但是不起作用)
        reset-enable: false
        # druid面板登录用户名/密码 默认不需要登录,设置了才需要。
        login-username: admin
        login-password: 123456

# 日志相关配置
logging:
  level:
    root: ERROR
  file:
    name: sys.log
  logback:
    rollingpolicy:
      # gz
      file-name-pattern: ${LOG_FILE}.%d{yyyy-MM-dd}.%i.zip
      max-file-size: 1MB
  pattern:
    dateformat: yyyy-MM-dd HH:mm:ss

mybatis:
  mapper-locations: classpath:mapper/*.xml
  # 如果指定了mybatis的扫描包,那么在mapper/*.xml中就不好再指定别的目录了,所以这里先注释。
#  type-aliases-package: com.xcg.webapp.model.entity

 启动后Druid监控页面:http://localhost:8100/druid/login.html  登录账户密码就是配置里面的 admin、123456
测试例子
IService

package com.xcg.webapp.IService;

import com.xcg.webapp.model.entity.Production;

import java.util.List;

/**
 * 商品IService
 */
public interface IProductionService {
    public List<Production> getAllList();
    public Production getModelById(int id);
    public int create(Production dto);
    public int create2(Production dto);
    List<Production> getListByName(String proName);
}

Service

package com.xcg.webapp.service;

import com.xcg.webapp.IService.IProductionService;
import com.xcg.webapp.mapper.ProductionMapper;
import com.xcg.webapp.model.entity.Production;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 商品Service
 */
@Service
public class ProductionService implements IProductionService {
    @Autowired
    private ProductionMapper productionMapper;

    /**
     * 查全部
     */
    @Override
    public List<Production> getAllList() {
        var list = productionMapper.getAllList();
        return list;
    }

    /**
     * 根据主键id查询
     */
    public Production getModelById(int id) {
        var dto = productionMapper.getModelById(id);
        return dto;
    }

    /**
     * 创建后返回成功行数
     */
    @Override
    public int create(Production dto) {
        return productionMapper.create(dto);
    }

    /**
     * 创建后返回主键id
     */
    @Override
    public int create2(Production dto) {
        return productionMapper.create2(dto);
    }

    /**
     * 品名模糊查询
     */
    @Override
    public List<Production> getListByName(String proName) {
        return productionMapper.getListByName("%" + proName + "%");
    }
}

Mapper

package com.xcg.webapp.mapper;

import com.xcg.webapp.model.entity.Production;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * 商品mapper
 */
@Mapper
public interface ProductionMapper {
    public List<Production> getAllList();
    public Production getModelById(@Param("id") int id);
    public int create(Production pro);
    public int create2(Production pro);
    /**
     * @Param("production_name") 参数名需要和sql脚本中的参数#{production_name}一致
     * */
    List<Production> getListByName(@Param("production_name") String proName);
}

/resources/mapper/ProductionMapper.xml

<?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.xcg.webapp.mapper.ProductionMapper">
    <!--当实体类中的 property 名称 和 数据库中的 column 名称不一致的时候,需要配置一个映射关系-->
    <resultMap id="BaseResultMap" type="com.xcg.webapp.model.entity.Production">
        <id property="productionId" column="production_id" jdbcType="INTEGER" javaType="int"/>
        <id property="productionCode" column="production_code" jdbcType="VARCHAR" javaType="String"/>
        <id property="productionName" column="production_name" jdbcType="VARCHAR" javaType="String"/>
        <id property="imgUrl" column="img_url" jdbcType="VARCHAR" javaType="String"/>
        <id property="spec" column="spec" jdbcType="VARCHAR" javaType="String"/>
        <id property="purchasePrice" column="purchase_price" jdbcType="DECIMAL" javaType="BigDecimal"/>
        <id property="salesPrice" column="sales_price" jdbcType="DECIMAL" javaType="BigDecimal"/>
        <id property="productionStatus" column="production_status" jdbcType="VARCHAR" javaType="String"/>
    </resultMap>

    <!--保存 返回受影响行数-->
    <insert id="create" parameterType="com.xcg.webapp.model.entity.Production" useGeneratedKeys="true" keyProperty="production_id">
        insert into production(production_code,production_name,img_url,spec,purchase_price,sales_price,production_status) values(#{production_code},#{production_name},#{img_url},#{spec},#{purchase_price},#{sales_price},#{production_status});
    </insert>
    <!--保存 返回新插入数据的主键-->
    <insert id="create2" parameterType="com.xcg.webapp.model.entity.Production">
        <selectKey keyProperty="production_id" keyColumn="production_id" order="AFTER" resultType="java.lang.Integer">SELECT LAST_INSERT_ID()</selectKey>
        insert into production(production_code,production_name,img_url,spec,purchase_price,sales_price,production_status) values(#{production_code},#{production_name},#{img_url},#{spec},#{purchase_price},#{sales_price},#{production_status});
    </insert>

    <!--获取集合-->
    <!-- 如果数据库字段和映射类属性一样,就可以直接使用resultType,否则必须使用resultMap配置字段和属性的映射关系。-->
    <!--resultMap="BaseResultMap"-->
    <!--resultType="com.xcg.webapp.model.entity.Production"-->
    <select id="getAllList" resultType="com.xcg.webapp.model.entity.Production">
        select * from production limit 10;
    </select>

    <!--获取单个-->
    <select id="getModelById" parameterType="INTEGER" resultType="com.xcg.webapp.model.entity.Production">
        select * from production where production_id=#{id};
    </select>

    <!--模糊查询-->
    <select id="getListByName" parameterType="String" resultType="com.xcg.webapp.model.entity.Production">
        select * from production where production_name like #{production_name};
    </select>
</mapper>

调用

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);
    @Autowired
    private ProductionService productionService;

    @GetMapping("/getProByName")
    public Object getProByName(@RequestParam String proName){
        var list = productionService.getListByName(proName);
        return list;
    }

 我用的SpringBoot 3.3.1 和 java17,所以能使用 var 声明变量。项目生成地址 https://start.spring.io/
连接oracle数据库连接字符串和驱动

db-type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: oracle.jdbc.driver.OracleDriver
        url: jdbc:oracle:thin:@//192.168.x.x:1521/service_name
        username: testdb
        password: abc123

 连接SqlServer驱动配置,连接字符串中 encrypt=false 不要启用SSL连接模式,不然会报错。

      db-type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
      url: jdbc:sqlserver://localhost:1433;DatabaseName=testdb;encrypt=false;trustServerCertificate=true;loginTimeout=30;
      username: sa
      password: 123456
      validation-query: SELECT 1 #测试连接是否可用的SQL语句
      initial-size: 10 #数据库连接池初始化连接数量
      min-idle: 10 #数据库连接池最小连接数量
      max-active: 30 #数据库连接池最大连接数量
      max-wait: 30000 # 配置获取连接等待超时的时间 30000毫秒(30秒)
      testOnBorrow: true # 申请连接时执行validationQuery检测连接是否有效
      testWhileIdle: true # 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
      timeBetweenEvictionRunsMillis: 60000 # 默认60秒。Destroy线程会检测连接的间隔时间,如果连接空闲时间大于等于minEvictableIdleTimeMillis则关闭物理连接。

 

posted on 2024-07-02 15:14  邢帅杰  阅读(61)  评论(0编辑  收藏  举报