8

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,976
  • 3
  • 19
  • 35
Jitindra Fartiyal
  • 107
  • 1
  • 1
  • 5

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,523
  • 17
  • 30
  • 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
  • do i need to implement all the methods of javax.persistance.EntityManager? – aarush gandhi73 Feb 10 '23 at 12:00
  • @aarushgandhi73 no need to implement all the methods, create a entityManager object and used pre-defined methods – TheSprinter Feb 13 '23 at 09:12
2

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
  • 4,011
  • 10
  • 39
  • 72