这就是我调用SQL Server存储过程的方式

public Response<List<CollectionItem>> getCollectionList(int customerId) {
        StoredProcedureQuery query = entityManager.createStoredProcedureQuery("Sp_Tab_GetCollectionInvoice");
        query.registerStoredProcedureParameter("CustomeriD", int.class, ParameterMode.IN);
        query.registerStoredProcedureParameter("Ccode", int.class, ParameterMode.IN);


        query.setParameter("CustomeriD", customerId);
        query.setParameter("Ccode", 1);

        List<CollectionItem> resultList = query.unwrap(Query.class)
                .setResultTransformer(Transformers.aliasToBean(CollectionItem.class)).getResultList();

        return new ResponseUtil().createResponse(resultList);

    }


这是pojo课

public class CollectionItem {

    public long ID;
    public String TransType;
    public long Invno;
    public String TDate;
    public double Amount;


    public CollectionItem(long ID, String TransType, long Invno, String TDate, double Amount) {
        this.ID = ID;
        this.TransType = TransType;
        this.Invno = Invno;
        this.TDate = TDate;
        this.Amount = Amount;
    }
}


但是它没有转换结果,而是给出了对象数组的列表

我如何正确地将对象数组映射到pojo类?

是否应该通过运行循环将对象数组手动转换为pojo?

最佳答案

我不是这个问题的专家,但是EntityManager.createStoredProdecureQuery有第二个参数用于指定返回类型。如下更改呼叫时会发生什么(还要注释设置ResultTransformer的行)?

StoredProcedureQuery query = entityManager.createStoredProcedureQuery("Sp_Tab_GetCollectionInvoice", CollectionItem.class);


如果上述解决方案不起作用,我怀疑从存储过程返回的列与所需的POJO类成员不匹配。您可以使用<sql-result-set-mapping>或相应的注释编写映射,以将结果集映射到类成员。据我所知,Hibernate的查询接口还具有以编程方式处理此映射的方法。您可能要检查addRoot()addProperty()方法。

注意:我只是注意到您的CollectionItem类没有用@Entity注释。我不确定上述解决方案是否可以在这种情况下使用。如果您不想添加@Entity并使用结果转换器,我想您的CollectionItem类需要一个没有参数的构造函数。为了使bean转换器正常工作,Hibernate要求该类没有构造函数或公共的无参数构造函数。

关于java - 如何在结果集转换器中使用 hibernate 存储过程查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58571157/

10-11 02:25
查看更多