14

I'm trying to map a non-entity pojo with the createNativeQuery method of entityManager of jpa. By using something like this

@SqlResultSetMapping(name="ResultMapping", 
classes={
@ConstructorResult(
     targetClass=Employee.class,
       columns={
          @ColumnResult(name="empID", type=Long.class),
          @ColumnResult(name="empName", type=String.class),
          }
   )
}
)
public class Loader{
 private EntityManager em;

 public void load(){

   Query query = em.createNativeQuery("select empID, empName from employee",  "ResultMapping");
   List<Employee> = query.getResultList();
 }

}

public class Employee{

 private long empID;
 private String empName;
 public Employee(long empid, String empname)
 {
     this.empID = empid;
     this.empName = empname;
 }
}

I getting unknown SqlResultSetMapping ResultMapping error Where I am supposed to put SqlResultSetMapping so that the entityManager will able to recognize it?

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47

1 Answers1

23

Where I am supposed to put SqlResultSetMapping so that the entityManager will able to recognize it?

As far as I can see it varies from a persistence provider:

  • EclipseLink: put it at any class in the classpath
  • Hibernate: put it at any class annotated with @Entity; in fact I am able to reproduce the error when I put it elsewhere:

    org.hibernate.MappingException: Unknown SqlResultSetMapping [ResultMapping]
    

Tested with EclipseLink 2.5.2, Hibernate 4.3.8.Final


In general to make your application portable across JPA providers it would be the best to put SqlResultSetMapping at any entity class.

wypieprz
  • 7,981
  • 4
  • 43
  • 46
  • 1
    JPA is specification while EclipseLink, Hibernate, OpenJPA, DataNucleus and others are its implementations (persistence providers). There is no such thing as 'pure JPA' because specification does not precise how a given persistence provider should behave in this particular case, although it might be specified in the future. – wypieprz May 15 '16 at 18:10
  • 1
    `put it at any class annotated with @Entity` Is there any widely used/ known convention of putting them somewhere. I have a bunch of queries and I do not want to pollute an entity with these. Also, my Queries are some Reporting use case queries and have no such strong connection with any single. – krozaine Sep 25 '19 at 08:53
  • 3
    @krozaine if you don’t want to pollute your entities with annotation blocks, you can define them in an XML mapping file with `sql-result-set-mapping` block. – wypieprz Sep 26 '19 at 12:43
  • it makes sense since you are mapping something retrieved from database – Guilherme Alencar Apr 01 '20 at 14:37