I needed some data from a old big oracle database. Most of the time I write or generate a entity class, and fetch the data with a Named Query. But this time I only needed two informations and I didn’t what to use a dozen primary keys and so on to find it. So I used a Native Query.. I know… messy.

Trying to make it look a little professional, I used a SqlResultSetMapping to map the result to a plain old java bean.

//Need to be put in an entity class. Any entity class will do
@SqlResultSetMapping(
        name = EntityClass.RESULT_MAPPING_NAME,
        classes = {
            @ConstructorResult(
                    targetClass = MyPlainBean.class,
                    columns = {
                        @ColumnResult(name = "something"),
                        @ColumnResult(name = "someone")
                    }
            )
        }
)

//EntityClass is the name of the plain bean - NOT an entity

//Some static final Strings to reference the information. Do not use the same string multiple times!
public static final String RESULT_MAPPING_NAME  = "aVeryGoodName";
public static final String NATIVE_SQL_QUERY  = "SELECT  column1 \"something\" column32 \"someone\" where.....";

//The Native Query call
final Query<MyPlainBean> query = session.createNativeQuery(EntityClass.NATIVE_SQL_QUERY,EntityClass.RESULT_MAPPING_NAME);