文档站点
Skip to content

数据库连接配置 ​

Laravel 的 .env 配 DB_HOST、DB_DATABASE,靠 Eloquent 查询;Spring Boot 在 application.yml 配 spring.datasource,然后有三种访问方式:JdbcTemplate(对应查询构建器)、Spring Data JPA(对应 Eloquent)、MyBatis(国内企业主流)。这篇先把「连上库」和三种方式选型讲清楚。

连接 MySQL ​

yaml
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/blog?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8
    username: root
    password: secret
    driver-class-name: com.mysql.cj.jdbc.Driver
Laravel .envSpring Boot application.yml
DB_HOST=localhost在 url 的 //localhost:3306 里
DB_PORT=3306在 url 的 //localhost:3306 里
DB_DATABASE=blog在 url 的 /blog 里
DB_USERNAME=rootspring.datasource.username
DB_PASSWORD=secretspring.datasource.password

TIP

连接串 jdbc:mysql://host:port/库名?参数 是 JDBC 的标准格式,参数用 & 分隔。serverTimezone 和 characterEncoding 是最常见的两个坑:不配会报时区错误或中文乱码。

加数据库驱动依赖 ​

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

TIP

驱动声明 runtime scope,因为它只在运行时需要(编译期用接口 DataSource 就够)。Spring Boot 自动配置会读 spring.datasource.* 创建 DataSource Bean —— 又是「自动配置」在帮你干活。

H2(开发用内存数据库) ​

不想装 MySQL,开发/测试用 H2:

yaml
spring:
  datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
    username: sa
    password:
xml
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

三种数据访问方式怎么选 ​

方式类比 Laravel特点什么时候用
JdbcTemplateQuery Builder + 原生 SQL手写 SQL,结果手动映射简单查询、复杂 SQL、不想要 ORM
Spring Data JPAEloquent ORM实体映射、自动 CRUD、关联关系大部分业务 CRUD,团队接受 ORM
MyBatis无直接对应(更像手写 DAO)SQL 完全自己写,XML/注解管理国内企业主流,SQL 优化可控

本教程怎么安排?

事务管理 ​

声明式事务:@Transactional ​

Laravel 用 DB::transaction(fn () => ...);Spring 用一个注解包住方法:

java
@Service
public class OrderService {

    @Transactional
    public void transfer(Long fromId, Long toId, BigDecimal amount) {
        accountDao.decrease(fromId, amount);
        accountDao.increase(toId, amount);
        // 方法正常结束 → 提交;抛异常 → 自动回滚
    }
}

TIP

@Transactional 默认在运行时异常时回滚(RuntimeException),受检异常(Exception)不回滚,可通过 @Transactional(rollbackFor = Exception.class) 调整。

@Transactional 的坑(和 @Async 一样)

  1. 同类内部调用失效:this.method() 不走代理。@Transactional 方法必须从 Bean 外部调用
  2. 只能 public 方法:private 方法上的注解无效
  3. 事务内做远程调用:长时间持锁,并发差,能异步就异步
  4. 记得先 commit 再发消息/邮件:见 事件机制 的 AFTER_COMMIT 监听器

编程式事务(少用) ​

java
@Service
public class OrderService {
    private final TransactionTemplate txTemplate;

    public OrderService(TransactionTemplate txTemplate) {
        this.txTemplate = txTemplate;
    }

    public void doWork() {
        txTemplate.executeWithoutResult(status -> {
            accountDao.decrease(1L, BigDecimal.TEN);
        });
    }
}

连接池 ​

Spring Boot 默认用 HikariCP(公认高性能连接池,无需额外配置),相关配置:

yaml
spring:
  datasource:
    hikari:
      maximum-pool-size: 20          # 最大连接数
      minimum-idle: 5                # 最小空闲
      connection-timeout: 30000      # 获取连接超时(ms)
      max-lifetime: 1800000          # 连接最大存活(ms)

TIP

连接池就是 Laravel 里 PHP-FPM 的长连接思想,但更成熟:HikariCP 自动创建/销毁/复用连接。大多数项目用默认值就行,别乱调。

常见问题速查 ​

报错原因
Access denied for user用户名/密码错,或没建库/授权
Unknown database 'blog'数据库不存在,先建库
The server time zone value '...'url 缺 serverTimezone=Asia/Shanghai
Public Key Retrieval is not allowedMySQL 8 加 allowPublicKeyRetrieval=true
Failed to configure a DataSource没配 spring.datasource 或没加驱动依赖
中文乱码url 加 characterEncoding=utf8 + 库表都 UTF-8

接下来,手写 SQL 的世界:查询构建器(JdbcTemplate)。

面向 PHP / Laravel 开发者的 Spring Boot 中文文档