6

The fundamental of ORM is mapping with the objects. But, for some reason, I don't want to create objects for running a query.

Is there any way, in which without creating entities (managed classes), I can run a native SQL query?

lospejos
  • 1,958
  • 3
  • 19
  • 33

2 Answers2

3

Yes. You can.

Create a method in the repository class with specific query (native query):

@Query(value="select * from emp", nativeQuery=true)
Object getAllFromEmp();

Keep this method in the repository interface and call it from the service class

Or you can use EntityManager object as below

Query q = entityManager.createNativeQuery("SELECT * FROM emp e");
List<Object[]> empObject= q.getResultList();
TheSprinter
  • 1,377
  • 14
  • 28
  • But, here I need to have a class of 'emp' and make it as an entity, else if not, it is throwing error. I don't want to create an 'emp' class( managed class ), or to better say, I don't want to use ORM for some use-case. I am designing reporting services and for that, I don't want to create class(managed entities) for every report – Jitindra Fartiyal Jun 21 '18 at 04:35
  • 1
    here **emp** is table name not class name and we are using **native query** not **HQL** here. – TheSprinter Jun 22 '18 at 05:40
1

Have a look at createNativeQuery

...
Query query = em.createNativeQuery("select ...");
...

And, I think you can find more about it in this thread: https://stackoverflow.com/a/2110860/672798

Muatik
  • 3,753
  • 7
  • 33
  • 68