在我目前的Spring Boot REST示例项目中,我有两个实体(Book
和BookSummary
)都由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;
}
关于PagingAndSortingRepository
和BooksController
实现,我假设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的以下行为吗?
答案 0 :(得分:2)
我猜Hibernate会感到困惑,因为您通过使用以下内容对两个类进行注释来命名两个具有相同实体名称的实体类:
@Entity(name = "Book")
在这种情况下,您应该只使用@Entity
并让Hibernate使用实体类的非限定名称。
每个实体创建一个存储库也是一种很好的做法:一个用于Book
实体,另一个用于BookSummary
实体。我不得不说,我从未见过用于两个不同实体的Spring Data存储库。无论如何,您的控制器逻辑可能如下:
@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);
}
}