用于数据库视图(非表)的 JPA/SpringBoot 存储库

Pau*_*ker 19 java hibernate jpa spring-data-jpa

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

然而,问题开始出现,它们有两个方面:

  1. 尝试设置正确的注释时。视图没有与之关联的主键,但如果没有在@javax.persistence.Id字段上正确注释,您将org.hibernate.AnnotationException: No identifier specified for entity在运行时得到一个抛出。

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

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

Rob*_*roj 21

我也在探索这个话题。我最终将 Spring Data JPA Interface-based Projections与本机查询一起使用。

我创建了一个界面,确保大写部分与数据库列名称匹配:

public interface R11Dto {

   String getTITLE();

   Integer getAMOUNT();

   LocalDate getDATE_CREATED();
}
Run Code Online (Sandbox Code Playgroud)

然后我为与视图没有任何关系的实体(用户)创建了一个存储库。在该存储库中,我创建了一个简单的本机查询。vReport1_1 是我的观点。

public interface RaportRepository extends JpaRepository<User, Long> {

   @Query(nativeQuery = true, value = "SELECT * FROM vReport1_1 ORDER BY DATE_CREATED, AMOUNT")
   List<R11Dto> getR11();

}
Run Code Online (Sandbox Code Playgroud)


Jan*_*han 16

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;
Run Code Online (Sandbox Code Playgroud)

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;

    ...
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 使用“@Subselect”创建合成 ID 并使用“@Immutable”帮助我成功地将视图映射到实体。 (2认同)
  • 对于 MSSQL,命令变为“select newid() as id, hs.* from Hunters_summary hs” (2认同)