Tuesday 26 November 2013

Native Query Mapping to Transient Fields of Entity class

Native queries are often a problem when comes to mapping with customized Entity classes. Especially classes with transient fields. To overcome this problem we have a special annotation available in JPA since version 1.0.
                                      @SqlResultSetMapping
That will do the trick for you!
This type of mapping is called scalar mapping. The only problem in choosing JPA is, the community is very limited and very limited resources are available internet. For complex JPA queries, most struggle to find a solution.
So I am going to show an example of mixing entity and scalar mapping.

@ColumnResult(name = "progress") does the scalar mapping. Remember that when you write your native query, It must have a column with alias progress.

For example: select p.*, count(*) as progress from project p
We can also use @SqlResultSetMapping to map different Entities from one native query. I will show this example in my next post.

1 comment:

  1. I'm having trouble getting the transient field to retain the value. Instead, the result set comes back as a List of Object[] with size of 2. The first Object in the Object[] is the Entity, but the transient field has the default value. The second Object in the Object[] is the correct value for the transient field. The only thing I am doing differently from this example is using a @NamedNativeQuery on the Entity.

    So with the tutorial example, I would add the following annotation to the Project:
    @NamedNativeQuery(name="selectWithCount", query="select p.*, count(*) as progress from project p", resultSetMapping="ProjectProgress")

    Then when I use that named query, I get the List of Object[] I mentioned in the first paragraph. Did you run into that? Do you know how to force the column to fill the transient field?
    Thanks,
    Dan

    ReplyDelete