gpt4 book ai didi

java - 用于数据库 View (而非表)的 JPA/Spring Boot 存储库

转载 作者:行者123 更新时间:2023-12-02 14:00:17 25 4
gpt4 key购买 nike

我正在尝试为 View 创建 JPA 实体。从数据库层来说,表和 View 应该是一样的。

但是,问题开始出现,有两个方面:

  1. 当尝试设置正确的注释时。 View 没有与其关联的主键,但也没有正确的 @javax.persistence.Id在字段上进行注释,您将得到 org.hibernate.AnnotationException: No identifier specified for entity在运行时抛出。

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

与缺少主键的 View 交互的正确 JPA/SpringBoot/Hibernate 方式是什么?

最佳答案

<强>1。使用数据库中的原生 SQL 创建 View ,

create or replace view hunters_summary as 
select
em.id as emp_id, hh.id as hh_id
from employee em
inner join employee_type et on em.employee_type_id = et.id
inner join head_hunter hh on hh.id = em.head_hunter_id;

<强>2。将其映射到“不可变实体”

package inc.manpower.domain;

import org.hibernate.annotations.Immutable;
import org.hibernate.annotations.Subselect;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;

@Entity
@Immutable
@Table(name = "`hunters_summary`")
@Subselect("select uuid() as id, hs.* from hunters_summary hs")
public class HuntersSummary implements Serializable {

@Id
private String id;
private Long empId;
private String hhId;

...
}

<强>3。现在使用您想要的方法创建存储库,

package inc.manpower.repository;

import inc.manpower.domain.HuntersSummary;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Repository
@Transactional
public interface HuntersSummaryRepository extends PagingAndSortingRepository<HuntersSummary, String> {
List<HuntersSummary> findByEmpRecruitedDateBetweenAndHhId(Date startDate, Date endDate, String hhId);
}

关于java - 用于数据库 View (而非表)的 JPA/Spring Boot 存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53508168/

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