搜索
首页Javajava教程Spring Boot 入门或 .NET 开发人员部分在 Spring Boot 中构建产品实体 CRUD 应用程序

Getting Started with Spring Boot or .NET Developers Part Building a Product Entity CRUD Application in Spring Boot

在上一篇文章中探索了 Spring Boot 3 的基础知识后,让我们通过实现 Product 实体 CRUD(创建、读取、更新、删除)操作来更深入地了解。在此过程中,我们将比较核心 Spring Boot 概念与 .NET Core 对应概念,以帮助弥合 .NET 开发人员过渡到 Java 生态系统的差距。

设置项目

开始之前,请确保您已准备好一个具有以下依赖项的 Spring Boot 项目:

  • Spring Web:用于构建 REST API。
  • Spring Data JPA:用于数据库交互。
  • PostgreSQL 驱动程序:用于连接到 PostgreSQL 数据库。

使用 Docker 在本地运行 PostgreSQL

要在本地运行 PostgreSQL,请使用 Docker 快速设置实例:

  1. 拉取 PostgreSQL 镜像:

    docker pull postgres
    
  2. 运行 PostgreSQL 容器:

    docker run --name postgres-db -e POSTGRES_PASSWORD=yourpassword -e POSTGRES_USER=yourusername -e POSTGRES_DB=mydatabase -p 5432:5432 -d postgres
    

    将您的用户名、您的密码和 mydatabase 替换为您想要的用户名、密码和数据库名称。

  3. 验证数据库正在运行:

    docker ps
    
  4. 使用数据库客户端(例如 DBeaver、pgAdmin 或 psql)连接到 localhost:5432 并验证您的数据库是否可访问。

更新 pom.xml 文件

如果您使用 Maven,请在 pom.xml 文件中包含以下依赖项,以确保所有必需的库可用:

<dependencies>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-data-jpa</artifactid>
    </dependency>
    <dependency>
        <groupid>org.postgresql</groupid>
        <artifactid>postgresql</artifactid>
        <version>42.5.0</version>
    </dependency>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-test</artifactid>
        <scope>test</scope>
    </dependency>
</dependencies>

此外,确保包含以下插件来构建项目:

<build>
    <plugins>
        <plugin>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-maven-plugin</artifactid>
        </plugin>
    </plugins>
</build>

与 .NET Core 的比较
在 .NET Core 中,包引用是使用 csproj 文件管理的。 PostgreSQL 支持的 Web API 的等效依赖项可能如下所示:

<itemgroup>
  <packagereference include="Microsoft.AspNetCore.App"></packagereference>
  <packagereference include="Npgsql.EntityFrameworkCore.PostgreSQL" version="6.0.0"></packagereference>
</itemgroup>

配置 PostgreSQL 数据库

更新您的 application.yml 文件以连接到 PostgreSQL 数据库:

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/mydatabase
    username: yourusername
    password: yourpassword
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
    hibernate:
      ddl-auto: update

将 mydatabase、yourusername 和 yourpassword 替换为您的实际 PostgreSQL 数据库详细信息。 ddl-auto=update 设置确保 Hibernate 根据您的实体定义自动创建或更新表。

与 .NET Core 的比较
在 .NET Core 中,类似的配置将驻留在 appsettings.json 中:

{
  "ConnectionStrings": {
    "DefaultConnection": "Host=localhost;Database=mydatabase;Username=yourusername;Password=yourpassword"
  },
  "EntityFramework": {
    "MigrationsAssembly": "YourProjectName"
  }
}

项目结构概述

Spring Boot 项目将代码组织到包中:

  • 实体:包含数据模型。
  • repository:数据库操作的接口。
  • 控制器:REST端点。
  • 服务(可选):业务逻辑。

此结构类似于 .NET Core 项目中的典型层:模型、数据/存储库、控制器和服务。

第 1 步:定义产品实体

在 Spring Boot 中,实体代表数据库表,类似于 Entity Framework Core 中的模型。使用 @Entity 和 @Id 等注释将类映射到表:

docker pull postgres

.NET Core 等效项

docker run --name postgres-db -e POSTGRES_PASSWORD=yourpassword -e POSTGRES_USER=yourusername -e POSTGRES_DB=mydatabase -p 5432:5432 -d postgres

第 2 步:创建存储库

在 Spring Boot 中,存储库是扩展 JpaRepository 的接口。它们提供内置的 CRUD 操作,类似于 EF Core 中的 DbContext。

docker ps

.NET Core 等效项

<dependencies>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-data-jpa</artifactid>
    </dependency>
    <dependency>
        <groupid>org.postgresql</groupid>
        <artifactid>postgresql</artifactid>
        <version>42.5.0</version>
    </dependency>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-test</artifactid>
        <scope>test</scope>
    </dependency>
</dependencies>

第 3 步:实现服务层(可选)

服务层处理业务逻辑。虽然是可选的,但对于大型应用程序来说这是一个很好的做法。

<build>
    <plugins>
        <plugin>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-maven-plugin</artifactid>
        </plugin>
    </plugins>
</build>

.NET Core 等效项

<itemgroup>
  <packagereference include="Microsoft.AspNetCore.App"></packagereference>
  <packagereference include="Npgsql.EntityFrameworkCore.PostgreSQL" version="6.0.0"></packagereference>
</itemgroup>

第 4 步:构建控制器

控制器处理 HTTP 请求,就像在 ASP.NET Core 中一样。

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/mydatabase
    username: yourusername
    password: yourpassword
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
    hibernate:
      ddl-auto: update

.NET Core 等效项

{
  "ConnectionStrings": {
    "DefaultConnection": "Host=localhost;Database=mydatabase;Username=yourusername;Password=yourpassword"
  },
  "EntityFramework": {
    "MigrationsAssembly": "YourProjectName"
  }
}

第 5 步:测试您的 API

运行您的应用程序并使用 Postman 或 cURL 等工具测试端点。确保您的 PostgreSQL 数据库正在运行并正确配置。

应用程序启动并运行后,使用 Postman 或 cURL 测试 CRUD 端点。确保 PostgreSQL 正在运行并正确配置。

使用 Postman 测试端点

  • GET /api/products:获取所有产品。
  • GET /api/products/{id}:通过 ID 获取单个产品。
  • POST /api/products:创建一个新产品。
  • DELETE /api/products/{id}:通过 ID 删除产品。

主要比较

Feature Spring Boot 3 .NET Core
Dependency Injection Built-in with @Autowired or constructor injection Built-in with AddScoped, AddSingleton
ORM Tool Spring Data JPA Entity Framework Core
Routing @RequestMapping, @GetMapping [Route], [HttpGet]
Middleware Spring Interceptors ASP.NET Middleware
Response Handling ResponseEntity IActionResult

结论

在 Spring Boot 中创建 CRUD 应用程序很简单,特别是对于那些熟悉 .NET Core 的人来说。依赖注入、ORM 和 RESTful API 的原理在两个生态系统中都很相似。本指南只是一个开始 - 未来的帖子将涵盖 Lombok 集成、Swagger/OpenAPI、验证、错误处理和数据库迁移。敬请期待!

编码愉快!


参考文献

  1. Spring Boot 文档:https://spring.io/projects/spring-boot
  2. PostgreSQL 文档:https://www.postgresql.org/docs/
  3. Spring Data JPA 文档:https://spring.io/projects/spring-data-jpa
  4. .NET Core 文档:https://docs.microsoft.com/en-us/aspnet/core/?view=aspnetcore-7.0

以上是Spring Boot 入门或 .NET 开发人员部分在 Spring Boot 中构建产品实体 CRUD 应用程序的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
JVM性能与其他语言JVM性能与其他语言May 14, 2025 am 12:16 AM

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生产性。1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

Java平台独立性:使用示例Java平台独立性:使用示例May 14, 2025 am 12:14 AM

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允许CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

JVM架构:深入研究Java虚拟机JVM架构:深入研究Java虚拟机May 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM:JVM与操作系统有关吗?JVM:JVM与操作系统有关吗?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java:写一次,在任何地方跑步(WORA) - 深入了解平台独立性Java:写一次,在任何地方跑步(WORA) - 深入了解平台独立性May 14, 2025 am 12:05 AM

Java实现“一次编写,到处运行”通过编译成字节码并在Java虚拟机(JVM)上运行。1)编写Java代码并编译成字节码。2)字节码在任何安装了JVM的平台上运行。3)使用Java原生接口(JNI)处理平台特定功能。尽管存在挑战,如JVM一致性和平台特定库的使用,但WORA大大提高了开发效率和部署灵活性。

Java平台独立性:与不同的操作系统的兼容性Java平台独立性:与不同的操作系统的兼容性May 13, 2025 am 12:11 AM

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允许Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

什么功能使Java仍然强大什么功能使Java仍然强大May 13, 2025 am 12:05 AM

JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

顶级Java功能:开发人员的综合指南顶级Java功能:开发人员的综合指南May 13, 2025 am 12:04 AM

Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),