9

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?

1

2 Answers 2

4

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();
Sign up to request clarification or add additional context in comments.

4 Comments

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
here emp is table name not class name and we are using native query not HQL here.
do i need to implement all the methods of javax.persistance.EntityManager?
@aarushgandhi73 no need to implement all the methods, create a entityManager object and used pre-defined methods
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.