Hibernate: select columns with their aliases

Consider this trivial query:

SELECT 1 as first, 2 as second

When using Hibernate we can do something like:

em.createNativeQuery(query).fetchResultList()

However, there seems to be no way to get aliases (or column names). This would be very useful for creating a List<Map<String, Object>> , where each map would be a string with their aliases, for example in this case: [{first: 1, second: 2}] .

Is there a way to do something like this?

+5
source share
2 answers

You can use the ResultTransformer interface. Implement custom mapping to display values ​​using aliases. here is an example https://vladmihalcea.com/why-you-should-use-the-hibernate-resulttransformer-to-customize-result-set-mappings/

With ResultTransformer, you can easily customize the type of result set, especially if you need aliases

+1
source

I would suggest a slightly different approach that can satisfy your needs.

JPA 2.1 has a feature called "displaying a result set."

Basically you should define a POJO class that will contain the result values ​​(all values ​​should be passed using the constructor):

 public class ResultClass{ private String fieldOne; private String fieldTwo; public ResultClass(String fieldOne, String fieldTwo){ this.fieldOne = fieldOne; this.fieldTwo = fieldTwo; } } 

Then you need to declare a match on one of your objects (no matter on what basis this should be declared by @Entity):

 @SqlResultSetMapping(name="ResultMapping", classes = { @ConstructorResult(targetClass = ResultClass.class, columns = {@ColumnResult(name="columnOne"), @ColumnResult(name="columnTwo")}) }) 

columnOne and columnTwo are aliases declared in the select clause of a custom query.

And finally, use in creating the query:

 List<ResultClass> results = em.createNativeQuery(query, "ResultMapping").getResultList(); 

In my opinion, this is more elegant and "above the level", since you do not work with generic Map key / value pairs, but with a specific POJO class.

+2
source

Source: https://habr.com/ru/post/1268897/


All Articles