用于数据库视图(非表)的 JPA/SpringBoot 存储库 [英] JPA/SpringBoot Repository for database view (not table)

查看:18
本文介绍了用于数据库视图(非表)的 JPA/SpringBoot 存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为视图创建 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:

  1. 尝试设置正确的注释时.视图没有与其关联的主键,但如果没有在字段上注释正确的 @javax.persistence.Id,您将收到 org.hibernate.AnnotationException: No identifier specified对于在运行时抛出的实体.

Spring Boot JpaRepository 接口定义要求 ID 类型扩展 Serializable,这排除了使用 java.lang.Void 作为视图实体上缺少 id 的解决方法.

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 基于接口使用本机查询进行投影.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆