在存储过程命名查询中映射自定义列名称

在存储过程命名查询中映射自定义列名称

本文介绍了Hibernate:在存储过程命名查询中映射自定义列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有以下命名查询包装存储过程: -

 < hibernate-mapping> 
< sql-query name =mySp>
< return-scalar column =name_firsttype =string/>
< return-scalar column =name_lasttype =string/>

{call some_sp:param}
< / sql-query>
< / hibernate-mapping>

name_first name_last 是存储过程返回的确切列名称。我创建了一个包含相同列名的bean,这样我就可以将查询的结果映射到该bean中。



pre $ public class MyBean {
private String name_first;
私人字符串name_last;

...
}

调用Hibernate代码命名查询并将结果映射到bean: -

pre $ MyBean myBean =(MyBean)sessionFactory.getCurrentSession()
.getNamedQuery(mySp)
.setParameter(param,param)
.setResultTransformer(Transformers.aliasToBean(MyBean.class))
.uniqueResult();

所有这些工作都很好,但不是依赖存储过程中的列名,而是想要在 MyBean 中使用我自己的列名,例如: -

 公共类MyBean {
私有字符串firstName; //而不是name_first
private String lastName; //而不是name_last

...
}

如何将我的列名映射到上述命名查询中的存储过程列?



谢谢。



UPDATE - 我在下面添加了我的最终解决方案。 您需要实施您自己的ResultTransformer 。这非常简单,您可以查看捆绑实现的来源以获取灵感。






I currently have the following named query that wraps around a stored procedure:-

<hibernate-mapping>
    <sql-query name="mySp">
        <return-scalar column="name_first" type="string" />
        <return-scalar column="name_last" type="string" />

        { call some_sp :param }
    </sql-query>
</hibernate-mapping>

The columns name_first and name_last are the exact column names returned by the stored procedure. I created a bean that contains the same column names so that I can map the queried result into that bean.

public class MyBean {
    private String  name_first;
    private String  name_last;

    ...
}

The Hibernate code that calls the named query and map the result into the bean:-

MyBean myBean = (MyBean) sessionFactory.getCurrentSession()
                        .getNamedQuery("mySp")
                        .setParameter("param", param)
                        .setResultTransformer(Transformers.aliasToBean(MyBean.class))
                        .uniqueResult();

All of these work fine, but instead of relying on the column names from the stored procedure, I want to use my own column names in MyBean, for example:-

public class MyBean {
    private String  firstName; // instead of name_first
    private String  lastName;  // instead of name_last

    ...
}

How do I map my column names against the stored procedure's columns in my named query above?

Thanks.

UPDATE - I added my final solution below.

解决方案

You'll need to implement your own ResultTransformer. It's really simple, and you can look at the source of the bundled implementations for inspiration.

http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/transform/ResultTransformer.html

https://github.com/hibernate/hibernate-core/tree/master/hibernate-core/src/main/java/org/hibernate/transform

这篇关于Hibernate:在存储过程命名查询中映射自定义列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 11:56