gpt4 book ai didi

Hibernate 命名实体的自动映射

转载 作者:行者123 更新时间:2023-12-03 02:56:23 24 4
gpt4 key购买 nike

在我当前的 Spring Boot REST 示例项目中,我有两个实体( BookBookSummary ),均由 PagingAndSortingRepository 提供。 。 Book实体如下所示:

@Entity(name = "Book")
public class Book
{
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
private UUID uuid;

private String title;

private String author;

private String publisher;

@Transient
private String type = "Book";

...[Getter & Setter]...
}

BookSummary实体如下所示:

@Entity(name = "Book")
public class BookSummary
{
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
private UUID uuid;

private String title;

private String author;

@Transient
private String type = "BookSummary";

...[Getter & Setter]...
}

PagingAndSortingRepository实体如下所示:

@Repository
public interface BookRepository extends PagingAndSortingRepository<Book, UUID>
{
Page<Book> findAll(Pageable pageable);
}

BooksRestController实体如下所示:

@RestController
@RequestMapping("/books")
public class BooksRestController
{
@GetMapping("/{uuid}")
public Book read(@PathVariable UUID uuid)
{
return bookRepository.findOne(uuid);
}

@GetMapping
public Page<Book> read(Pageable pageable)
{
return bookRepository.findAll(pageable);
}

@Autowired
private BookRepository bookRepository;
}

关于PagingAndSortingRepositoryBooksController实现时,我假设 REST 服务将提供 Book 的集合通过 /books 的实体路线。然而,该路线提供了 BookSummary 的集合。实体:

{
content: [
{
uuid: "41fb943e-fad4-11e7-8c3f-9a214cf093ae",
title: "Some Title",
author: "Some Guy",
type: "BookSummary"
},
...
]
}

books/41fb943e-fad4-11e7-8c3f-9a214cf093ae然而路线提供了 Book摘要(如预期):

{
uuid: "41fb943e-fad4-11e7-8c3f-9a214cf093ae",
title: "Some Title",
author: "Some Guy",
publisher: "stackoverflow.com"
type: "Book"
}

有人可以帮助我理解 Hibernate 的以下行为吗?

最佳答案

我猜 Hibernate 会感到困惑,因为您通过使用以下注释来命名两个具有相同实体名称的实体类:

@Entity(name = "Book")

在这种情况下,您应该简单地使用@Entity并让Hibernate使用实体类的非限定名称。

为每个实体创建一个存储库也是一种很好的做法:一个用于 Book 实体,第二个用于 BookSummary 实体。我不得不说,我从未见过 Spring Data 存储库用于两个不同的实体。无论如何,您的 Controller 逻辑可能如下:

@RestController
@RequestMapping("/books")
public class BooksRestController
{
private final BookRepository bookRepository;
private final BookSummaryRepository bookSummaryRepository;

@Autowired
public BooksRestController(BookRepository bookRepository, BookSummaryRepository bookSummaryRepository)
{
this.bookRepository = bookRepository;
this.bookSummaryRepository = bookSummaryRepository;
}

@GetMapping("/{uuid}")
public BookSummary read(@PathVariable UUID uuid)
{
return bookSummaryRepository.findOne(uuid);
}

@GetMapping
public Page<Book> read(Pageable pageable)
{
return bookRepository.findAll(pageable);
}
}

关于Hibernate 命名实体的自动映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48285195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com