我已经搜索了stackoverflow和其他站点,但是我不知道如何在Spring应用程序中使用Hibernate映射postgres函数返回的表。
我甚至不确定postgres函数的返回类型表是否能以某种方式与MyCustomTable匹配。
我试图用hibernate从spring应用程序调用postgres函数(存储过程)。
我有这个postgres函数

CREATE OR REPLACE FUNCTION func99(type text,start_date TIMESTAMP, end_date TIMESTAMP) RETURNS TABLE(
    some_day TIMESTAMP,
    tot_requests BIGINT)
 AS $$
 BEGIN
   RETURN QUERY
   SELECT t1.first_date, COUNT(*) FROM table1 t1
   WHERE t1.request_type = type and t1.first_date > start_date and t1.first_date < end_date;
 END;
 $$ LANGUAGE PLpgSQL;

控制器
@GetMapping("/users/{username}/func99")
    public List<MyCustomTable> getResultsFromFunc99(@PathVariable(value = "username") String username,
                                                 @CurrentUser UserPrincipal currentUser,
                                                 @RequestParam(value = "service_type") String type,
                                                 @RequestParam(value = "start_date") Timestamp startDate,
                                                 @RequestParam(value = "end_date") Timestamp endDate){

        return queryService.getResultsFromFunc99(username, currentUser, type, startDate, endDate);
    }

服务
public List<MyCustomTable> getResultsFromFunc99(String username, UserPrincipal currentUser, String type, Timestamp startDate, Timestamp endDate) {

        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new ResourceNotFoundException("User", "username", username));


        return return incidentRepository.func99(type, startDate, endDate);

存储库
@Procedure(procedureName = "func99")
    List<MyCustomTable> func99(String type, Timestamp startDate, Timestamp endDate);

实体
@Entity
@NamedStoredProcedureQuery(
        name = "func99",
        procedureName = "func99",
        parameters = {
                @StoredProcedureParameter(name = "type", mode = ParameterMode.IN, type = String.class),
                @StoredProcedureParameter(name = "start_date", mode = ParameterMode.IN, type = Timestamp.class),
                @StoredProcedureParameter(name = "end_date", mode = ParameterMode.IN, type = Timestamp.class)
        }
)
@Table(name = "table1")
public class MyCustomTable {...}

当postgres函数返回一个整数时,我可以让它工作。如何映射postgres函数返回的表以及如何将其与Hibernate集成?
非常感谢您的帮助!
谢谢!

最佳答案

这是一个我用来解决类似问题的解决方法,但它可能会起作用。
按如下方式定义SqlResultSetMapping:

@SqlResultSetMapping(
    name = "MyCustomTableMapping",
    entities = @EntityResult(entityClass = MyCustomTable.class)
)

然后将此参数更改为NamedStoredProcedureQuery注释:
resultSetMappings = "MyCustomTableMapping"

我将此技术与NamedNativeQueries一起使用,以确保Hibernate不会像跟踪实际实体那样跟踪它们的更改。使我和我的同事不必记住要有很多实体。几乎每一个关于如何使用与表不对应的搜索结果的教程都会给您留下这个问题,并将其视为正常。

07-26 00:50