Skip to content
Getting Started

在 Spring Boot 中使用 Supabase

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

AI 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 检查
  • curlunzip,用于下载并解压生成的项目

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.

1
curl https://start.spring.io/starter.zip \
2
-d dependencies=web,data-jpa,postgresql \
3
-d type=maven-project \
4
-d language=java \
5
-d groupId=com.example \
6
-d artifactId=instruments \
7
-d name=instruments \
8
-o instruments.zip
9
unzip instruments.zip -d instruments && cd instruments

3. 安装 Supabase 的代理技能(可选) #

🌐 3. Install Supabase's Agent Skills (optional)

Supabase 的 Agent Skills 是一套精心整理的指令,给你的 AI 代理提供关于如何使用 Supabase 的操作知识。

🌐 Supabase's Agent Skills is a curated set of instructions that give your AI agent procedural knowledge about working with 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.

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

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

1
npx skills add supabase/agent-skills

4. 设置 Postgres 连接详情 #

🌐 4. Set up the Postgres connection details

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

🌐 Navigate to your project dashboard and click on Connect.

会话池(端口 5432)下,选择JDBC标签并复制连接字符串。用你保存的数据库密码替换密码占位符,并p百分号编码其中包含的任何保留字符,比如 &#? 或空格。

🌐 Under the Session pooler (port 5432), select the JDBC tab and copy the connection string. Replace the password placeholder with your saved database password, and percent-encode any reserved characters it contains, such as &, #, ?, or a space.

连接字符串包含你的数据库密码,而 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.

1
export SUPABASE_DB_URL='jdbc:postgresql://aws-[REGION].pooler.supabase.com:5432/postgres?user=postgres.[PROJECT-REF]&password=[YOUR-PASSWORD]&sslmode=require'

你复制的字符串没有设置 sslmode,所以需要加上它。驱动默认使用 prefer,如果加密尝试失败,会回退到以明文发送数据。你也可以在数据库端强制启用 SSL

🌐 The string you copied doesn't set sslmode, so add it. The driver defaults to prefer, which falls back to sending your data in plaintext if the encrypted attempt fails. You can also enforce SSL on the database side.

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

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

src/main/resources/application.properties
1
spring.datasource.url=${SUPABASE_DB_URL}
2
spring.datasource.driver-class-name=org.postgresql.Driver
3
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.

在开始之前先从 Table Editor 创建架构,因为你的应用需要它。然后在 application.properties 中将 Hibernate 指向它。

🌐 Create the schema from the Table Editor as your app will need it before start. Then point Hibernate at it in application.properties.

src/main/resources/application.properties
1
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
1
package com.example.instruments;
2
3
import jakarta.persistence.Entity;
4
import jakarta.persistence.GeneratedValue;
5
import jakarta.persistence.GenerationType;
6
import jakarta.persistence.Id;
7
import jakarta.persistence.Table;
8
9
@Entity
10
@Table(name = "instruments")
11
public class Instrument {
12
13
@Id
14
@GeneratedValue(strategy = GenerationType.IDENTITY)
15
private Long id;
16
17
private String name;
18
19
public Instrument() {}
20
21
public Instrument(String name) {
22
this.name = name;
23
}
24
25
public Long getId() {
26
return id;
27
}
28
29
public String getName() {
30
return name;
31
}
32
33
public void setName(String name) {
34
this.name = name;
35
}
36
}

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

🌐 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
1
package com.example.instruments;
2
3
import org.springframework.data.jpa.repository.JpaRepository;
4
5
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
1
package com.example.instruments;
2
3
import org.springframework.boot.CommandLineRunner;
4
import org.springframework.boot.SpringApplication;
5
import org.springframework.boot.autoconfigure.SpringBootApplication;
6
import org.springframework.context.annotation.Bean;
7
8
@SpringBootApplication
9
public class InstrumentsApplication {
10
11
public static void main(String[] args) {
12
SpringApplication.run(InstrumentsApplication.class, args);
13
}
14
15
@Bean
16
CommandLineRunner seedInstruments(InstrumentRepository instrumentRepository) {
17
return args -> {
18
if (instrumentRepository.count() == 0) {
19
instrumentRepository.save(new Instrument("violin"));
20
instrumentRepository.save(new Instrument("viola"));
21
instrumentRepository.save(new Instrument("cello"));
22
}
23
};
24
}
25
}

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
1
package com.example.instruments;
2
3
import java.util.List;
4
5
import org.springframework.web.bind.annotation.GetMapping;
6
import org.springframework.web.bind.annotation.RestController;
7
8
@RestController
9
public class InstrumentController {
10
11
private final InstrumentRepository instrumentRepository;
12
13
public InstrumentController(InstrumentRepository instrumentRepository) {
14
this.instrumentRepository = instrumentRepository;
15
}
16
17
@GetMapping("/instruments")
18
public List<Instrument> getInstruments() {
19
return instrumentRepository.findAll();
20
}
21
}

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.

1
./mvnw spring-boot:run

下一步 #

🌐 Next steps