用于数据库视图的JPA/SpringBoot存储库(非表) [英] JPA/SpringBoot Repository for database view (not table)
问题描述
我正在尝试为视图创建JPA实体.在数据库层中,表和视图应该相同.
I'm attempting to create a JPA entity for a view. From the database layer, a table and a view should be the same.
但是,问题开始出现并且有两个方面:
However, problems begin to arise and they are two fold:
-
尝试设置正确的注释时.视图没有与之关联的主键,但是如果没有在字段上注释正确的
@javax.persistence.Id
,则在运行时会抛出org.hibernate.AnnotationException: No identifier specified for entity
.
When attempting to setup the correct annotations. A view does not have a primary key associated with it, yet without the proper
@javax.persistence.Id
annotated upon a field, you will get anorg.hibernate.AnnotationException: No identifier specified for entity
thrown at Runtime.
Spring Boot JpaRepository
接口定义要求ID
类型扩展Serializable
,这排除了使用java.lang.Void
作为解决方案的一种变通方法,因为该方法在视图实体上缺少id. p>
The Spring Boot JpaRepository
interface definition requires that the ID
type extends Serializable
, which precludes utilizing java.lang.Void
as a work-around for the lack of an id on an view entity.
与缺乏主键的视图进行交互的正确JPA/SpringBoot/Hibernate方法是什么?
What is the proper JPA/SpringBoot/Hibernate way to interact with a view that lacks a primary key?
推荐答案
我也正在探讨该主题.我最终使用了Spring Data JPA 界面-原生查询的基于Projections的投影.
I was exploring that topic too. I ended up using Spring Data JPA Interface-based Projections with native queries.
我创建了一个接口,确保大写部分与数据库列名称匹配:
I created an interface, making sure the UPPERCASE part matches the DB Column names:
public interface R11Dto {
String getTITLE();
Integer getAMOUNT();
LocalDate getDATE_CREATED();
}
然后,我为一个与视图没有任何关系的实体(用户)创建了一个存储库.在该存储库中,我创建了一个简单的本地查询. vReport1_1是我的观点.
Then i created a repository, for an Entity (User) not related in any way to the view. In that repository i created a simple native query. vReport1_1 is my view.
public interface RaportRepository extends JpaRepository<User, Long> {
@Query(nativeQuery = true, value = "SELECT * FROM vReport1_1 ORDER BY DATE_CREATED, AMOUNT")
List<R11Dto> getR11();
}
这篇关于用于数据库视图的JPA/SpringBoot存储库(非表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!