jpa 将postgres存储过程转换为java查询时出现问题

ykejflvf  于 2022-11-14  发布在  Java
关注(0)|答案(1)|浏览(162)

我正在迁移一个数据库。在旧的数据库中,我们使用了一些存储过程- SP,我们希望在新的数据库中将其删除。我们只是希望使用普通的Java查询,而不是SP。我们将从Java Sping Boot 应用程序中调用查询。
下面是SP

CREATE OR REPLACE PROCEDURE public.spfetchowner(
    owner integer,
    optype integer,
    INOUT p_refcur refcursor)
LANGUAGE 'plpgsql'
AS $BODY$
BEGIN
    OPEN p_refcur FOR
    SELECT
        z.owner_num, 
        COALESCE(op_type_num, optype) AS op_type_num, 
        ad.sunday, ad.monday, ad.tuesday, ad.wednesday, ad.thursday, ad.friday, ad.saturday
        FROM (SELECT owner AS owner_num) AS z
        LEFT OUTER JOIN owner_details AS ad
            ON z.owner_num = ad.owner_num AND op_type_num = optype;
END;
$BODY$;

ALTER PROCEDURE public.spfetchowner(integer, integer, refcursor)
    OWNER TO postgres;

我的DB表详细信息:

owner_num integer NOT NULL,
    op_type_num integer NOT NULL,
    sunday numeric(5,3),
    monday numeric(5,3),
    tuesday numeric(5,3),
    wednesday numeric(5,3),
    thursday numeric(5,3),
    friday numeric(5,3),
    saturday numeric(5,3),
    CONSTRAINT pk_owner_details PRIMARY KEY (owner_num, op_type_num)

这是我从owner_details中获取详细信息的java存储库方法

@Query(nativeQuery = true,
        value = "I need the proper equivalent query from the SP here")
OwnerDetails fetchOwnerDetailsByOwnerNumAndOpType(
        @Param("ownerNum") Integer owner, 
        @Param("typeNum") Integer type );

我无法从我需要在回购方法中使用的SP形成查询。有人能在查询形成部分帮助我吗?简单的选择是工作,但我需要选择查询作为SP中的框架与连接,然后如何在我的回购方法中使用相同的。

wnrlj8wa

wnrlj8wa1#

为查询(@Query)指定参数时,基本上有两个选项
选项1(使用命名参数)

@Query(nativeQuery = true,
    value = "SELECT
    z.owner_num, 
    COALESCE(op_type_num, optype) AS op_type_num, 
    ad.sunday, ad.monday, ad.tuesday, ad.wednesday, ad.thursday, ad.friday, ad.saturday
    FROM (SELECT :ownerNum AS owner_num) AS z
    LEFT OUTER JOIN owner_details AS ad
        ON z.owner_num = ad.owner_num AND op_type_num = :typeNum")
   OwnerDetails fetchOwnerDetailsByOwnerNumAndOpType(
    @Param("ownerNum") Integer owner, 
    @Param("typeNum") Integer type );

或选项2(使用序数加上?)

@Query(nativeQuery = true,
    value = "SELECT
    z.owner_num, 
    COALESCE(op_type_num, optype) AS op_type_num, 
    ad.sunday, ad.monday, ad.tuesday, ad.wednesday, ad.thursday, ad.friday, ad.saturday
    FROM (SELECT ?1 AS owner_num) AS z
    LEFT OUTER JOIN owner_details AS ad
        ON z.owner_num = ad.owner_num AND op_type_num = ?2")
 OwnerDetails fetchOwnerDetailsByOwnerNumAndOpType(
    Integer owner, 
    Integer type );

相关问题