在 Spring Boot 中使用 Supabase
Learn how to create a Spring Boot project and connect it to your Supabase project.
先决条件 #
🌐 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.
想通过编程创建一个项目吗?
使用 管理 API 或向 MCP 服务器 请求创建一个新的 Supabase 项目。
🌐 Use the Management API or ask the MCP server to create a new Supabase project.
安全地保存你的数据库密码。你连接数据库时需要它。
🌐 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.
1curl 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.zip9unzip instruments.zip -d instruments && cd instruments3. 安装 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:
1npx skills add supabase/agent-skills4. 设置 Postgres 连接详情 #
🌐 4. Set up the Postgres connection details
导航到你的项目仪表板,然后点击连接。
🌐 Navigate to your project dashboard and click on Connect.
交易池(端口 6543)不能作为你应用的主要数据源,因为 Spring Data JPA 使用 Hibernate,而 Hibernate 依赖服务器端预处理语句。如果你在 IPv6 环境 中或有 IPv4 插件,请使用会话池,或者直接使用连接字符串。
🌐 The Transaction pooler (port 6543) doesn't work as your app's main data source, because Spring Data JPA uses Hibernate, which relies on server-side prepared statements. Use the Session pooler, or the direct connection string if you're in an IPv6 environment or have the IPv4 Add-On.
在会话池(端口 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.
如果你忘记了数据库密码,可以在你的数据库设置中重置。
🌐 You can reset your database password in your Database Settings if you do not have it.
连接字符串包含你的数据库密码,而 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.
1export 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.
1spring.datasource.url=${SUPABASE_DB_URL}2spring.datasource.driver-class-name=org.postgresql.Driver3spring.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.
1spring.jpa.properties.hibernate.default_schema=app6. 创建一个实体和仓库 #
🌐 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.
1package com.example.instruments;23import jakarta.persistence.Entity;4import jakarta.persistence.GeneratedValue;5import jakarta.persistence.GenerationType;6import jakarta.persistence.Id;7import jakarta.persistence.Table;89@Entity10@Table(name = "instruments")11public class Instrument {1213 @Id14 @GeneratedValue(strategy = GenerationType.IDENTITY)15 private Long id;1617 private String name;1819 public Instrument() {}2021 public Instrument(String name) {22 this.name = name;23 }2425 public Long getId() {26 return id;27 }2829 public String getName() {30 return name;31 }3233 public void setName(String name) {34 this.name = name;35 }36}在同一个包里创建一个 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.
1package com.example.instruments;23import org.springframework.data.jpa.repository.JpaRepository;45public 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.
1package com.example.instruments;23import org.springframework.boot.CommandLineRunner;4import org.springframework.boot.SpringApplication;5import org.springframework.boot.autoconfigure.SpringBootApplication;6import org.springframework.context.annotation.Bean;78@SpringBootApplication9public class InstrumentsApplication {1011 public static void main(String[] args) {12 SpringApplication.run(InstrumentsApplication.class, args);13 }1415 @Bean16 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.
1package com.example.instruments;23import java.util.List;45import org.springframework.web.bind.annotation.GetMapping;6import org.springframework.web.bind.annotation.RestController;78@RestController9public class InstrumentController {1011 private final InstrumentRepository instrumentRepository;1213 public InstrumentController(InstrumentRepository instrumentRepository) {14 this.instrumentRepository = instrumentRepository;15 }1617 @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