不执行通过 @query 注释对 Postgresql 的本机 sql 查询

The native sql query to Postgresql via the @query annotation is not executed

为了获得必要的数据,我对 PostgreSQL 形成了一个 SQL 查询,这是一组相关的视图表:

1) CREATE or replace view camera_layout AS
select layout_id, unnest(layout.camera_ids) as camera_id from layout

2) CREATE or replace view camera_region AS
select c.camera_id as camera_id ,object.region_id
FROM object LEFT JOIN camera c on object.object_id = c.object_id WHERE object.region_id = ?1

3) CREATE or replace view region_layout AS
select distinct cl.layout_id from camera_layout cl,
camera_region cr where cl.camera_id in (select cr.camera_id from camera_region cr)

4) SELECT l from layout l where l.layout_id in (select rl.layout_id from region_layout rl)


当我从控制台依次在数据库中执行这些查询时,一个接一个,一切正常。

但是,如果您 运行 通过 @query 注释(“...”,NativeQuery = true)在存储库中进行类似查询,则会发生许多错误,并且查询最终会崩溃,而不会return正在处理任何事情。这怎么可能,我该怎么办?

我的服务是这样的:

存储库:


@Repository
public interface LayoutRepository extends JpaRepository<Layout,Integer> {

 @Query(value = "create or replace view camera_layout AS\n" +
         "select layout_id, unnest(layout.camera_ids) as camera_id from layout" ,
          nativeQuery = true)
    void createViewLayoutCamera();

 @Query(value = "CREATE or replace view camera_region AS\n" +
            "select c.camera_id as camera_id ,object.region_id\n" +
            "FROM object LEFT JOIN camera c on object.object_id = c.object_id WHERE object.region_id = ?1 " +
            "",nativeQuery = true)
    void createViewCameraRegion(Integer region);


    @Query(value = "create or replace view region_layout AS\n" +
            " select distinct cl.layout_id from camera_layout cl,\n" +
            "camera_region cr where cl.camera_id in (select cr.camera_id from camera_region cr)",nativeQuery = true)
    void createViewRegionLayout();

   @Query( value = "select l from layout l where l.layout_id in (select rl.layout_id from region_layout rl)",nativeQuery = true)
    List <Layout> filterRegion();


服务:

   @Override
    public List<LayoutDTO> filterRegion(Integer region_id) {

        ArrayList<LayoutDTO> convert_objects = new ArrayList<>();

        LayoutDTO conv_object;

     layoutRepository.createViewLayoutCamera();


     layoutRepository.createViewCameraRegion(region_id);

  
     layoutRepository.createViewRegionLayout();

     List <Layout> objects = layoutRepository.filterRegion();



当尝试执行 .It returns "the query did not return results" 时,Hibernate SQL 调试器说只有查询号 1 有效。 "Hibernate: 创建或替换视图 camera_layout AS select layout_id, unnest(layout.camera_ids) as camera_id from layout” 其余的分解,虽然他们应该工作帮助我,我非常感谢提前

As stated here DDL 语句需要使用 @Modifying 注释进行注释,因此您的存储库方法应如下所示:

@Modifying
@Query(value = "create or replace view camera_layout AS\n" +
         "select layout_id, unnest(layout.camera_ids) as camera_id from layout" ,
          nativeQuery = true)
void createViewLayoutCamera();