Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create native SQL query without creating entity class in SpringBoot

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?

like image 541
Jitindra Fartiyal Avatar asked Jun 20 '18 20:06

Jitindra Fartiyal


People also ask

How write native SQL query in spring boot?

We can use @Query annotation to specify a query within a repository. Following is an example. In this example, we are using native query, and set an attribute nativeQuery=true in Query annotation to mark the query as native. We've added custom methods in Repository in JPA Custom Query chapter.

What is the difference between JPQL and native query?

In JPA, you can create a query using entityManager. createQuery() . You can look into API for more detail. Native query refers to actual sql queries (referring to actual database objects).


Video Answer


2 Answers

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();
like image 165
TheSprinter Avatar answered Oct 06 '22 19:10

TheSprinter


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

like image 35
Muatik Avatar answered Oct 06 '22 19:10

Muatik