Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

java - Hibernate: Mapping custom column names in stored procedure named query

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...