views:

2073

answers:

2

I have the following Java 6 code:

    Query q = em.createNativeQuery( 
        "select T.* " +
        "from Trip T join Itinerary I on (T.itinerary_id=I.id) " +
        "where I.launchDate between :start and :end " +
        "or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end",
        "TripResults" );

    q.setParameter( "start", range.getStart(), TemporalType.DATE );
    q.setParameter( "end", range.getEnd(), TemporalType.DATE );

    @SqlResultSetMapping( name="TripResults",
        entities={
            @EntityResult( entityClass=TripEntity.class ),
            @EntityResult( entityClass=CommercialTripEntity.class )
        }
    )

I receive a syntax error on the last closing right parenthesis. Eclipse gives: "Insert EnumBody to complete block statement" and "Insert enum Identifier to complete EnumHeaderName". Similar syntax error from javac.

What am I doing wrong?

+2  A: 

The Hibernate annotations docs (http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/) suggest that this should be a class-level annotation rather than occurring inline within your code. And indeed when I paste that code into my IDE and move it around, the compile errors are present when the annotation is inline, but vanish when I put it in above the class declaration:

@SqlResultSetMapping( name="TripResults",
        entities={
            @EntityResult( entityClass=TripEntity.class ),
            @EntityResult( entityClass=CommercialTripEntity.class )
        }
    )
public class Foo {
   public void bogus() {
      Query q = em.createNativeQuery( 
        "select T.* " +
        "from Trip T join Itinerary I on (T.itinerary_id=I.id) " +
        "where I.launchDate between :start and :end " +
        "or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end",
        "TripResults" );

      q.setParameter( "start", range.getStart(), TemporalType.DATE );
      q.setParameter( "end", range.getEnd(), TemporalType.DATE );
   }
}

...obviously I have no evidence that the above code will actually work. I have only verified that it doesn't cause compile errors.

Jim Kiley
A: 

Your example comes straight out of the API docs which are unfortunately poorly presented.

Your annotation should be placed on some class, probably the one in which you will be creating the query to use the result set mapping. However, it actually doesn't matter where this annotation is placed. Your JPA provider will actually maintain a global list of all these mappings, so no matter where you define it, you will be able to use it anywhere.

This is a shortcoming of the annotation method (as opposed to specifying things in XML.) Many other things in the JPA (i.e. named queries) are defined this same way. It makes it seem like there's some kind of connection between the thing being defined and the class on which it is annotated, when it's not.

Ryono