AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-23393804

FinnCoal's questions

Martin Hope
FinnCoal
Asked: 2025-02-10 03:01:21 +0800 CST

Spring Boot - 如何/在哪里将 DTO 的外键转换为实体

  • 5

我正在使用 Spring Boot 创建一个 REST 服务,但在将 JSON 请求/DTO 转换为相应实体时遇到了麻烦,特别是当一个实体包含对另一个实体的引用时。例如,假设我们有这些对象:

data class BookEntity(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Int?,

    val name: String,

    @ManyToOne
    @JoinColumn(name = "author_id")
    val author: AuthorEntity,
)
data class AuthorEntity(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Int?,

    val name: String,
)
data class BookRequestDto(
    val name: String,
    val authorId: Int,
)

该应用程序具有控制器-服务-存储库层,据我所知,我应该在控制器层中执行 DTO -> 实体转换,然后将生成的实体传递给服务层。但是,为了将图书请求 DTO 转换为实体,我首先必须根据给定的从存储库中获取适当的 Author 实体authorId。我的问题是:我到底应该在哪里做这件事?

鉴于服务层应该只接受实体,看来我应该在控制器层中获取作者。但这意味着 Book 控制器需要访问 Author 服务层,我不确定这是否是好的做法。

这就是我的意思(使用明显的扩展函数来执行 DTO/实体转换)

@RestController
@RequestMapping(path = ["/books"])
class BookController(
    private val bookService: BookService,
    private val authorService: AuthorService,
) {
    @PostMapping
    fun createBook(@RequestBody bookDto: BookRequestDto): ResponseEntity<BookResponseDto> {
        val author = authorService.get(bookDto.authorId)
        val bookEntity = bookDto.toBookEntity(author = author)
        val createdBook = bookService.create(bookEntity)
        return ResponseEntity(createdBook.toBookResponseDto(), HttpStatus.CREATED)
    }
}

这是通常的做法吗?还是在控制器中混合多个服务是个坏主意?我显然必须在某个地方访问作者存储库,但我不知道最佳位置在哪里。有没有更好的方法?

spring
  • 1 个回答
  • 72 Views
Martin Hope
FinnCoal
Asked: 2025-02-05 02:29:21 +0800 CST

执行更新时 save() 不会返回生成的列

  • 5

我是一名 Spring Boot 初学者,在使生成的值正常工作方面遇到了麻烦。我希望让数据库 (Postgres) 在插入行时生成一个时间戳列,而不是让 Spring 生成它,但问题是 Spring 在执行更新时似乎不会从数据库中选择时间戳。

当我添加新实体时save(),它会顺利插入数据库,并生成一个时间戳并返回给 Spring;一切正常。当我尝试访问find()现有实体时,也会返回时间戳,所以这也很好。但是,当我尝试更新现有实体时,Spring 不会访问数据库中的时间戳,而是为相应字段返回 null。

这是实体定义:

import jakarta.persistence.*
import org.hibernate.annotations.CurrentTimestamp
import org.hibernate.generator.EventType
import java.time.OffsetDateTime

@Entity(name = "users")
@Table(name = "users")
data class User(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Int?,

    val name: String,

    @Column(name = "date_created")
    @CreationTimestamp(source = SourceType.DB)
    val dateCreated: OffsetDateTime?,
)

假设数据库已经有了一行,例如1 | 2025-01-02 02:03:04 | user1。像这样的 PUT 请求{ name: "new user" }将更新name数据库中的字段而不更改时间戳,但 JPA 返回的更新实体将是{ id: 1, name: "new user", dateCreated: null }。我不确定这是为什么。我知道 JPA 在 INSERTing 新行时会执行额外的 SELECT 以获取 Postgres 生成的时间戳,但我不明白为什么它在 UPDATEing 时不直接获取已经存在的时间戳。

为了完整性,控制器和服务类:

import com.example.hello.User
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping(path = ["/users"])
class UserController(private val userService: UserService) {
    @PostMapping
    fun createStaff(@RequestBody user: User): ResponseEntity<User> {
        val createdUser = userService.create(user)
        return ResponseEntity(createdUser, HttpStatus.CREATED)
    }

    @PutMapping(path = ["/{id}"])
    fun updateUser(@PathVariable("id") id: Int, @RequestBody user: User): ResponseEntity<User> {
        val updatedUser = userService.update(id, user)
        return ResponseEntity(updatedUser, HttpStatus.OK)
    }

    @GetMapping(path = ["/{id}"])
    fun readUser(@PathVariable("id") id: Int): ResponseEntity<User> {
        val user = userService.get(id)
        return user?.let { ResponseEntity.ok(it) } ?: ResponseEntity(HttpStatus.NOT_FOUND)
    }
}
import com.example.hello.User
import com.example.hello.UserRepository
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service

@Service
class UserService(private val userRepository: UserRepository) {
    fun create(user: User): User {
        return userRepository.save(user)
    }

    fun update(id: Int, user: User): User {
        val userWithId = user.copy(id = id)
        return userRepository.save(userWithId)
    }

    fun get(id: Int): User? {
        return userRepository.findByIdOrNull(id)
    }
}
spring-boot
  • 2 个回答
  • 34 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve