Skip to content
Getting Started

在 Spring Boot 中使用 Supabase

Learn how to create a Spring Boot project and connect it to your Supabase project.

Agent Prompt

Help me add Supabase to my Spring Boot project. Create a Supabase project at database.new. Then:

  1. Run curl https://start.spring.io/starter.zip -d dependencies=web,data-jpa,postgresql -d type=maven-project -d language=java -d groupId=com.example -d artifactId=instruments -d name=instruments -o instruments.zip and unzip it to scaffold the project.
  2. Copy the JDBC connection string for the Session pooler (port 5432) from the Supabase Connect panel and export it as a SUPABASE_DB_URL environment variable, so the password stays out of source control. Set spring.datasource.url=${SUPABASE_DB_URL} and spring.datasource.driver-class-name in application.properties. Avoid the Transaction pooler (port 6543) since Hibernate relies on prepared statements.
  3. Set spring.jpa.hibernate.ddl-auto=update and spring.jpa.properties.hibernate.default_schema in application.properties, so Hibernate creates tables outside the public schema that Supabase exposes as a data API.
  4. Create an Instrument JPA entity mapped to the instruments table with @Table(name = "instruments"), and an InstrumentRepository extending JpaRepository.
  5. Add a CommandLineRunner bean to InstrumentsApplication that seeds the table with a few instruments the first time the app starts.
  6. Create an InstrumentController with a GET /instruments endpoint that returns instrumentRepository.findAll().
  7. Run ./mvnw spring-boot:run and open http://localhost:8080/instruments.

REFERENCE https://supabase.com/docs/guides/getting-started/quickstarts/spring-boot.md

先决条件 #

🌐 Prerequisites

在开始之前,确保你有:

🌐 Before you begin, make sure you have:

  • Java 17 或更高版本,你可以用 java -version 检查
  • curl 和 unzip,用于下载并解压生成的项目

1. 创建一个 Supabase 项目 #

🌐 1. Create a Supabase project

首先,你需要一个 Supabase 项目。

🌐 To start, you need a Supabase project.

从你所属的任何组织的仪表板创建一个新的 Supabase 项目。

🌐 Create a new Supabase project from the Dashboard of any organization you belong to.

安全地保存你的数据库密码。你连接数据库时需要它。

🌐 Save your database password securely. You need it for the connection string.

2. 创建一个 Spring Boot 项目 #

🌐 2. Create a Spring Boot project

使用 Spring Initializr 创建一个新的项目,添加 Web、Spring Data JPA 和 Postgres 驱动依赖。从你存放项目的目录运行以下命令。

🌐 Use Spring Initializr to scaffold a new project with the Web, Spring Data JPA, and Postgres Driver dependencies. Run the following from the directory where you keep your projects.

curl https://start.spring.io/starter.zip \
-d dependencies=web,data-jpa,postgresql \
-d type=maven-project \
-d language=java \
-d groupId=com.example \
-d artifactId=instruments \
-d name=instruments \
-o instruments.zip
unzip instruments.zip -d instruments && cd instruments

3. 设置 AI 工具(可选) #

🌐 3. Set up AI tooling (optional)

Supabase 提供了两种方式让 AI 工具了解你的项目:Agent Skills,它为你的 AI 编程助手提供操作知识;以及 MCP 服务器,它可以让 AI 助手直接连接到你的 Supabase 项目。

🌐 Supabase provides two ways to give AI tools context about your project: Agent Skills, which give your AI coding agent procedural knowledge, and the MCP server, which connects AI assistants to your Supabase project directly.

代理技能 #

🌐 Agent Skills

代理技能 是一套精心整理的指令,提供你的 AI 代理有关使用 Supabase 的操作知识。

安装它们,这样你的 AI 编码代理就能使用当前的 Supabase 模式(比如认证、服务端渲染和数据库迁移)生成更准确、更可靠的代码,而不只是依赖培训数据。

🌐 Install them so your AI coding agent can produce more accurate, reliable code using current Supabase patterns, such as authentication, server-side rendering, and database migrations, rather than relying solely on training data.

安装代理技能 #

🌐 Installing Agent Skills

要安装,在你项目的根目录运行以下命令:

🌐 To install, run the following command in the root of your project:

npx skills add supabase/agent-skills

Supabase MCP 服务器 #

🌐 Supabase MCP server

Supabase MCP 服务器将 AI 助手连接到 Supabase,这样它们就可以检查你的架构并代表你操作项目。在 MCP 文档 中了解如何将它添加到你的客户端。

🌐 The Supabase MCP server connects AI assistants to Supabase, so they can inspect your schema and act on your projects on your behalf. Find out how to add it to your client in the MCP docs.

4. 设置 Postgres 连接详情 #

🌐 4. Set up the Postgres connection details

  1. 导航到你的项目仪表板,然后点击连接。

  2. 找到会话池连接字符串并复制它。将密码占位符替换为你保存的数据库密码,并对其中的任何保留字符进行百分号编码,比如 &、#、? 或空格。如果你没有数据库密码,可以在你的数据库设置中重置它。

  3. 如果你的框架单独设置它,可以在连接字符串上或作为显式配置选项设置 sslmode=require。大多数驱动默认使用 prefer,如果加密尝试失败,就会回退到以明文发送数据。你也可以在数据库端强制使用 SSL。

下面的连接字符串只是显示格式。请从你复制的字符串中获取主机、端口和用户名,而不是直接输入括号里的占位符。

🌐 The connection strings below show the format only. Take the host, port, and username from the string you copied rather than typing the bracketed placeholders literally.

选择 JDBC 标签,以便复制适用于 Spring Boot 的正确格式的连接字符串。

🌐 Select the JDBC tab to copy the connection string in the right format for Spring Boot.

连接字符串包含你的数据库密码,而 application.properties 已经和你的项目一起提交了。最好将这个字符串设置为环境变量,并在你部署的任何平台上用相同的方式设置它。

🌐 The connection string contains your database password, and application.properties is committed with your project. Set the string as an environment variable instead, and set it the same way on whatever platform you deploy to.

export SUPABASE_DB_URL='jdbc:postgresql://[POOLER-HOST]:5432/postgres?user=postgres.[PROJECT-REF]&password=[YOUR-PASSWORD]&sslmode=require'

然后在 src/main/resources/application.properties 中引用该变量和驱动程序。

🌐 Then reference the variable, along with the driver, in src/main/resources/application.properties.

src/main/resources/application.properties
spring.datasource.url=${SUPABASE_DB_URL}
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=update

如果应用在使用 Unable to determine Dialect without JDBC metadata 时启动失败,Hibernate 根本无法建立连接。查看日志中那行上面的内容来找到真正的原因,最常见的是 password authentication failed。

🌐 If the app fails to start with Unable to determine Dialect without JDBC metadata, Hibernate couldn't open a connection at all. Look above that line in the logs for the real cause, most commonly password authentication failed.

5. 更改默认模式 #

🌐 5. Change the default schema

默认情况下,Hibernate 会在 public 架构中创建表。我们建议更改这一设置,因为 Supabase 会将 public 架构作为 数据 API 暴露出来。

🌐 By default Hibernate creates tables in the public schema. We recommend changing this as Supabase exposes the public schema as a data API.

在启动应用之前先创建 app 架构。Hibernate 会在启动时在该架构中创建表,但它不会自己创建架构。在 SQL 编辑器 中运行以下命令:

🌐 Create the app schema before you start the app. Hibernate creates tables in that schema on startup, but it does not create the schema itself. Run the following in the SQL Editor:

create schema if not exists app;

然后让 Hibernate 指向 application.properties 里的 schema。

🌐 Then point Hibernate at the schema in application.properties.

src/main/resources/application.properties
spring.jpa.properties.hibernate.default_schema=app

6. 创建一个实体和仓库 #

🌐 6. Create an entity and repository

Spring Data JPA 将 Java 类映射到数据库表。在 src/main/java/com/example/instruments/Instrument.java 中创建一个 Instrument 实体。当设置了 spring.jpa.hibernate.ddl-auto=update 后,Hibernate 会在应用启动时为你创建 instruments 表。

🌐 Spring Data JPA maps Java classes to database tables. Create an Instrument entity in src/main/java/com/example/instruments/Instrument.java. With spring.jpa.hibernate.ddl-auto=update set, Hibernate creates the instruments table for you when the app starts.

src/main/java/com/example/instruments/Instrument.java
package com.example.instruments;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "instruments")
public class Instrument {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
public Instrument() {}
public Instrument(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

在同一个包里创建一个 InstrumentRepository 接口。继承 JpaRepository 就能得到 findAll、save 和其他查询方法,而无需编写任何实现。

🌐 Create an InstrumentRepository interface in the same package. Extending JpaRepository gives you findAll, save, and other query methods without writing any implementation.

src/main/java/com/example/instruments/InstrumentRepository.java
package com.example.instruments;
import org.springframework.data.jpa.repository.JpaRepository;
public interface InstrumentRepository extends JpaRepository<Instrument, Long> {}

7. 初始化示例数据 #

🌐 7. Seed sample data

在 InstrumentsApplication.java 中添加一个 CommandLineRunner bean,用于在应用第一次启动时保存一些示例乐器。

🌐 Add a CommandLineRunner bean to InstrumentsApplication.java that saves some sample instruments the first time the app starts.

src/main/java/com/example/instruments/InstrumentsApplication.java
package com.example.instruments;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class InstrumentsApplication {
public static void main(String[] args) {
SpringApplication.run(InstrumentsApplication.class, args);
}
@Bean
CommandLineRunner seedInstruments(InstrumentRepository instrumentRepository) {
return args -> {
if (instrumentRepository.count() == 0) {
instrumentRepository.save(new Instrument("violin"));
instrumentRepository.save(new Instrument("viola"));
instrumentRepository.save(new Instrument("cello"));
}
};
}
}

8. 从应用中查询数据 #

🌐 8. Query data from the app

创建一个 InstrumentController,通过仓库获取 instruments 表的每一行,并以 JSON 返回。

🌐 Create an InstrumentController that fetches every row from the instruments table through the repository and returns it as JSON.

src/main/java/com/example/instruments/InstrumentController.java
package com.example.instruments;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class InstrumentController {
private final InstrumentRepository instrumentRepository;
public InstrumentController(InstrumentRepository instrumentRepository) {
this.instrumentRepository = instrumentRepository;
}
@GetMapping("/instruments")
public List<Instrument> getInstruments() {
return instrumentRepository.findAll();
}
}

9. 启动应用 #

🌐 9. Start the app

运行 Spring Boot 应用,然后在浏览器中打开 http://localhost:8080/instruments。你应该能看到乐器列表。

🌐 Run the Spring Boot app, and go to http://localhost:8080/instruments in your browser. You should see the list of instruments.

./mvnw spring-boot:run

生产要求 #

🌐 Production requirements

本指南中的快速入门步骤是为了让你尽快运行起一个可用的应用,而不是为了生产环境优化。

🌐 The quickstart procedure in this guide optimizes for getting you to a working app, not for production.

在你部署之前:

🌐 Before you deploy:

  • 如果你的应用通过数据 API 读取或写入数据,请查看你的 行级安全 策略。你在这里添加的任何策略都是针对这个快速入门的示例数据,而不是针对真实用户数据。
  • 在你部署的平台上把 Supabase 凭据设置为环境变量,而不是把它们提交到源码管理里。
  • 一旦你准备上线,就为你的 Supabase 项目配置一个自定义域名。

下一步 #

🌐 Next steps