Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute a native SQL script in JPA/Hibernate?

I have a SQL script with database dump. How can I execute it using Hibernate's EntityManager?

I tried it this way:

EntityManager manager = getEntityManager();  Query q = manager.createNativeQuery(sqlScript); q.executeUpdate(); 

but it works only when sqlScript contains a single SQL query, while I need to run multiple inserts and other complex stuff.

RDBMS: Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production

like image 376
Anke Avatar asked Jan 16 '13 12:01

Anke


People also ask

Can we execute native SQL query in Hibernate?

Hibernate provide option to execute native SQL queries through the use of SQLQuery object. Hibernate SQL Query is very handy when we have to execute database vendor specific queries that are not supported by Hibernate API.

How use native SQL query in Hibernate?

You can use native SQL to express database queries if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. Hibernate 3. x allows you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.

Can we use native query in JPA repository?

You can implement these operations using JPQL, Criteria, or native queries. You can use the @Query annotation to define such a JPQL or native SQL statement. Because write operations need to be executed differently than read operations, you also need to annotate the repository method with a @Modifying annotation.


1 Answers

Wrap your query with begin end block. Like

EntityManager manager = getEntityManager();  Query q = manager.createNativeQuery("BEGIN " + sqlScript + " END;"); q.executeUpdate(); 
like image 132
hkutluay Avatar answered Oct 08 '22 09:10

hkutluay